你应该知道的 14 个 JavaScript 数组技巧
1. 如何使用数组解构
2. 如何创建无重复版本的数组
3. 如何查找符合条件的所有元素
4. 如何从数组中删除所有假值
5. 如何查找符合条件的第一个元素
6. 如何检查是否有任何/每个元素符合条件
7. 如何求两个数组的交集
8. 如何求两个数组的差
9. 如何求两个数组的并集
10. 如何检索第一个和最后一个元素
11. 如何将元素添加到数组的前面/后面
12. 如何复制数组
13. 如何从数组中找出最小值和最大值
14. 如何对数字数组进行排序
结论
这篇文章最初发表在kais.blog上。
让我们一起进步! 关注我的 Twitter,获取每日开发者技巧。感谢您阅读我的内容!
更新:别忘了查看你可能不知道的 10 个很棒的 JavaScript 字符串技巧!
数组无处不在。每当你使用 JavaScript 时,你都可能用到数组。程序员通常会使用特定的库来提升数组的易用性。然而,我想向你展示 14 个关于 JavaScript 数组的实用技巧,这些技巧你可能还不知道。这样,你就可以摆脱外部依赖。不妨用这些简单的代码片段来代替。
- 如何使用数组解构
- 如何创建无重复版本的数组
- 如何查找符合条件的所有元素
- 如何从数组中删除所有假值
- 如何查找符合条件的第一个元素
- 如何检查是否有任何/每个元素符合条件
- 如何求两个数组的交集
- 如何找出两个数组的差
- 如何求两个数组的并集
- 如何检索第一个和最后一个元素
- 如何将元素添加到数组的前面/后面
- 如何复制数组
- 如何从数组中查找最小值和最大值
- 如何对数字数组进行排序
1. 如何使用数组解构
使用数组解构,你可以从 JavaScript 数组中提取单个元素。请看以下示例:
const fruits = ["🍎", "🍌", "🍒"];
const apple = fruits[0];
console.log(apple); // "🍎"
const banana = fruits[1];
console.log(banana); // "🍌"
const cherry = fruits[2];
console.log(cherry); // "🍒"
我们可以使用数组解构来重写相同的内容:
const [apple, banana, cherry] = ["🍎", "🍌", "🍒"];
console.log(apple); // "🍎"
console.log(banana); // "🍌"
console.log(cherry); // "🍒"
太棒了!此外,您还可以跳过某些元素,如果您愿意的话:
const [apple, , cherry] = ["🍎", "🍌", "🍒"];
console.log(apple); // "🍎"
console.log(cherry); // "🍒"
注意上面的空位。你可以跳过任何不需要的元素,只需省略变量名并添加另一个逗号即可。
此外,使用数组解构还可以做另外两件很棒的事情:
// Assign a default value for a missing element.
const [apple, banana, cherry, melon = "🍉"] = ["🍎", "🍌", "🍒"];
console.log(melon); // "🍉"
// Get all remaining elements from an array using the rest operator (`...`).
const [apple, ...remainingFruits] = ["🍎", "🍌", "🍒"];
console.log(remainingFruits); // ["🍌", "🍒"]
数组解构还能实现更多功能。我以后可能会再写一篇文章来专门讲解。
2. 如何创建无重复版本的数组
要从数组中删除所有重复项,人们经常使用像 这样的库lodash
。这个库本身并不差,但是,还有一种更简单的方法。您可以获取所有唯一值,而无需任何外部依赖。为此,请Set
从数组中创建一个新数组。然后,使用扩展运算符 ( ...
) 从集合中创建一个新数组。由于集合只能保存唯一值,因此不会留下任何重复项。
const fruits = ["🍎", "🍌", "🍌", "🍒", "🍎"];
// Create a new set from `fruits`, thereby removing all duplicates.
// Then, create a new array from it.
const uniqueFruits = [...new Set(fruits)];
console.log(uniqueFruits); // ["🍎", "🍌", "🍒"]
3. 如何查找符合条件的所有元素
如果您正在处理数组,有时您可能想删除一些元素。也许您想删除奇数,或者您只是想查找短字符串。无论您想做什么,都可以使用Array#filter
这个方法。
const names = ["Kai", "Katharina", "Tim"];
// Keep names that are shorter than 4 characters.
const shortNames = names.filter(name => name.length < 4);
console.log(shortNames); // ["Kai", "Tim"]
// Find names that are longer than 10 characters.
const extraLongNames = names.filter(name => name.length > 10);
console.log(extraLongNames); // []
4. 如何从数组中删除所有假值
有时,你的数组包含虚假值,你想删除它们。虚假值包括false
、null
、0
、""
、undefined
和NaN
。你可以很容易地将它们过滤掉。为此,你可以Array#filter
再次使用该方法,并简单地检查元素的真实性:
const fruits = ["🍎", false, "🍌", undefined, "🍒"];
// Keep all array elements where `fruit` is truthy.
const filteredFruits = fruits.filter(fruit => fruit);
console.log(filteredFruits); // ["🍎", "🍌", "🍒"]
// This shows an alternative way to remove all falsy values from an array.
const filteredFruits = fruits.filter(Boolean);
5. 如何查找符合条件的第一个元素
与 3. 类似,有时我们只需要第一个符合条件的元素。因此,我们可以使用此Array#find
方法。
const names = ["Kai", "Katharina", "Tim"];
// Find a name that is shorter than 4 characters.
const shortName = names.find(name => name.length < 4);
console.log(shortName); // "Kai"
// Find a name that is longer than 10 characters.
const extraLongName = names.find(name => name.length > 10);
console.log(extraLongName); // undefined
6. 如何检查是否有任何/每个元素符合条件
JavaScript 数组实现了两个很棒的方法:Array#some
和Array#every
。我经常注意到很多人不知道这两个方法。你可以用它们来检查任意元素 ( Array#some
) 或所有元素 ( Array#every
) 是否符合特定条件。
const names = ["Kai", "Katharina", "Tim"];
// Check if ANY name is shorter than 4 characters.
const containsShortName = names.some(name => name.length < 4);
console.log(containsShortName); // true
// Check if EVERY name is longer than 3 characters.
const containsLongNamesOnly = names.every(name => name.length > 3);
console.log(containsLongNamesOnly); // false
7. 如何求两个数组的交集
比较两个数组时,你可能想知道哪些元素同时包含在两个数组中。这意味着,我们需要求两个数组的交集。因此,我们可以使用Array#filter
和的组合Array#includes
。
const fruitsA = ["🍎", "🍌", "🍒"];
const fruitsB = ["🍒", "🍆", "🍉", "🍌"];
const intersection = fruitsA.filter(fruit => fruitsB.includes(fruit));
console.log(intersection); // ["🍌", "🍒"]
8. 如何求两个数组的差
与 7 类似,我们可以使用组合Array#filter
和Array#includes
查找两个数组之间的差异。具体实现取决于是否要包含第二个数组中的相关元素。
const fruitsA = ["🍎", "🍌", "🍒"];
const fruitsB = ["🍒", "🍆", "🍉", "🍌"];
// Keep all elements from `fruitsA` that are not included in `fruitsB`.
const difference = fruitsA.filter(fruit => !fruitsB.includes(fruit));
console.log(difference); // ["🍎"]
// Keep all elements from `fruitsA` that are not included in `fruitsB` and vice versa.
const difference = [
...fruitsA.filter(fruit => !fruitsB.includes(fruit)),
...fruitsB.filter(fruit => !fruitsA.includes(fruit)),
];
console.log(difference); // ["🍎", "🍆", "🍉"]
9. 如何求两个数组的并集
也许你想合并两个数组并删除所有重复项。还好你已经在技巧 2 中学习了如何删除重复项。我们将...
再次使用扩展运算符 () 和集合。
const fruitsA = ["🍎", "🍌", "🍒"];
const fruitsB = ["🍒", "🍆", "🍉", "🍌"];
// Merge `fruitsA` and `fruitsB`. Then, use a set for removing duplicates.
// After that, create a new array from the set.
const union = [...new Set([...fruitsA, ...fruitsB])];
console.log(union); // ["🍎", "🍌", "🍒", "🍆", "🍉"]
10. 如何检索第一个和最后一个元素
有时,您唯一感兴趣的元素是第一个或最后一个元素。访问它们的一种直接方法是使用Array#shift
和Array#pop
方法。但是,请注意,这些方法会从数组中删除第一个和最后一个元素。有时,您不想更改原始数组。
const fruits = ["🍎", "🍌", "🍒"];
// Find the first element. Attention! This modifies the original array.
const first = fruits.shift();
console.log(first); // "🍎"
// Find the last element. Attention! This modifies the original array.
const last = fruits.pop();
console.log(last); // "🍒"
// Remember, both methods modify the original array.
console.log(fruits); // ["🍌"]
11. 如何将元素添加到数组的前面/后面
你可能已经了解了这一点。但为了以防万一,我还是会告诉你如何在 JavaScript 数组的前面添加或后面添加元素。虽然几乎每个人都知道如何在数组的末尾添加元素,但有时人们不知道如何在数组的开头添加元素。我会向你展示这两种方法。此外,我还会向你展示如何一次添加多个元素。
const fruits = ["🍎", "🍌", "🍒"];
// Append an element with `Array#push`.
// This means, we'll add it to the end.
fruits.push("🍉");
console.log(fruits); // ["🍎", "🍌", "🍒", "🍉"];
// Prepend an element with `Array#unshift`.
// This means, we'll add it to the beginning.
fruits.unshift("🍆");
console.log(fruits); // ["🍆", "🍎", "🍌", "🍒", "🍉"];
// You can also add multiple items at once.
// Works with `push` and `unshift`.
fruits.push("🍍", "🍊");
fruits.unshift("🍍", "🍊");
// Also, you could use the spread operator (...).
// This would add all elements from another array.
fruits.push(...["🍍", "🍊"]);
fruits.unshift(...["🍍", "🍊"]);
12. 如何复制数组
正如您在之前的技巧中看到的,某些操作会更改原始数组。有时这是不可取的。因此,我们需要以某种方式复制它。一个简单的方法是使用Array#slice
方法。
// This example is similar to tip 11.
const fruitsA = ["🍎", "🍌", "🍒"];
// Here, we copy the `fruitsA` array.
const fruitsB = fruitsA.slice();
// Find the first element. Attention! This modifies our `fruitsB` array.
const first = fruitsB.shift();
console.log(first); // "🍎"
// Find the last element. Attention! This modifies our `fruitsB` array.
const last = fruitsB.pop();
console.log(last); // "🍒"
// This time, our original arrays stays intact.
// Only `fruitsB` has changed.
console.log(fruitsA); // ["🍎", "🍌", "🍒"]
console.log(fruitsB); // ["🍌"]
// This shows an alternative way to copy an array.
const fruitsB = [...fruitsA];
注意!这不会创建深层复制。对象和嵌套数组是通过引用传递的。因此,假设fruitsA
包含一个对象,您将该数组复制到 中fruitsB
。然后,您将从 中取出该对象fruitsB
并进行修改。您可能认为这会保持初始数组的完整性。但是,很遗憾,您错了。您从 中检索的对象fruitsB
仍然引用了 中的对象fruitsA
。因此,对 中对象的任何更改fruitsB
都将镜像到 中的同一对象fruitsA
。记住这一点很重要!对于深层复制,请考虑使用专用库。
13. 如何从数组中找出最小值和最大值
如果你要处理大量的数字,那么就需要找出最小值或最大值。你可能知道可以使用Math#min
and Math#max
。将它与展开运算符 ( ...
) 结合使用,你就可以轻松地检查整个数组的最小值和最大值。
const priceHistory = [450, 500, 330, 600, 910];
// Find the minimum value.
const minimumPrice = Math.min(...priceHistory);
console.log(minimumPrice); // 330
// Find the maximum value.
const maximumPrice = Math.max(...priceHistory);
console.log(maximumPrice); // 910
14. 如何对数字数组进行排序
如果要对数组进行排序,您可能会使用Array#sort
。但是,数字的排序方式与您想象的不同。在 JavaScript 中对数组进行排序时,默认情况下会将元素转换为字符串。然后,通过比较元素的 UTF-16 码位对元素进行排序。对于数字,这可能会导致意外的顺序。因此,我们将更改默认行为,并将一个函数传递给该Array#sort
方法。它的工作原理是每次始终比较两个元素(a
和b
)。如果结果小于 0,a
则优先比较。如果结果大于 0,则b
优先比较。
const numbers = [15, 52, 23, 11, 9];
// Sort in ascending order. Attention! This modifies the original array.
numbers.sort((a, b) => a - b);
console.log(numbers); // [9, 11, 15, 23, 52]
// Sort in descending order. Attention! Again, this modifies the original array.
numbers.sort((a, b) => b - a);
console.log(numbers); // [52, 23, 15, 11, 9]
结论
数组可以用于各种各样的事情。通常,有一些简单的原生方法可以完成这项工作。也许你已经了解这些技巧,也许还没有。无论如何,我希望这篇文章能让你感兴趣。我会尝试在未来更新这篇文章,添加新的技巧。
非常感谢您阅读这篇文章。请考虑与您的朋友和同事分享。期待与您再次相见!
更新:别忘了查看你可能不知道的 10 个很棒的 JavaScript 字符串技巧!
让我们一起进步! 关注我的 Twitter,获取每日开发者技巧。感谢您阅读我的内容!
这篇文章最初发表在kais.blog上。
文章来源:https://dev.to/kais_blog/14-awesome-javascript-array-tips-you-should-know-about-1d0m