- ForEach
循环 遍历数组中每个元素并执行回调函数
const arr = [1, 2, 3];
arr.forEach(num => console.log(num));
// Console: 1, 2, 3
- Map
循环遍历数组中的每个元素并执行回调函数。使用回调函数的返回值需要创建一个新数组
const arr = [1, 2, 3, 4, 5];
const areEven = arr.map(num => num % 2 === 0);
console.log(areEven); // Console: [false, true, false, true, false]
- Filter
循环遍历数组中的每个元素,并仅选择符合条件的元素,根据所选元素返回一个新数组
const arr = [1, 2, 3, 4, 5];
const evenNumbers = arr.filter(num => num % 2 === 0);
console.log(evenNumbers); // Console [2, 4]
- Find
查找数组中满足条件的第一个元素。如果没有找到,将返回 undefined。
const arr = [1, 2, 3, 4, 5];
const firstEvenNumber = arr.find(num => num % 2 === 0);
console.log(firstEvenNumber); // Console [2]
- FindIndex
查找数组中满足条件的第一个元素索引,它返回满足给定条件的第一个元素的索引,如果没有找到,则返回-1
const arr = [1, 2, 3, 4, 5];
const firstEvenNumberIdx = arr.findIndex(num => num % 2 === 0);
console.log(firstEvenNumberIdx);
- Reduce
回调将累加器作为第一个参数,回调的返回值成为下一次迭代的累加器
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, num) => acc + num, 0);
console.log(sum); // Console: 15
- Every
此方法接受一个返回布尔值的回调。如果条件对数组中的所有元素都有效,那么 Every() 将返回 true。
const arr = [1, 2, 3, 4, 5];
const areAllEven = arr.every(num => num % 2 === 0);
console.log(areAllEven); // Console: false
- Some
这个方法也接受一个返回布尔值的回调。如果条件对至少一个元素有效,Some() 将返回 true
const arr = [1, 2, 3, 4, 5];
const isOneEven = arr.some(num % 2 === 0);
console.log(isOneEven); // true
- Sort
它按升序对数组进行排序。它需要一个回调函数,有两个元素——a 和 b。如果 a 小于 b,则返回 -1,否则返回 1。
如果它们相等,则返回 0。
const arr = [1, 2, 3, 4, 5];
const descendingArr = arr.sort((a, b) => b - a);
console.log(descendingArr);
- Flat
Flat 用于将嵌套数组展平为单个数组。您可以指定将数组展平的深度。
const arr = [[[1, 2], [3]], [4, 5]];
const flattenedArr = arr.flat(4);
console.log(flattenedArr); // Console [1, 2, 3, 4, 5]
- Reverse
反转数组中元素的顺序。
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.reverse();
console.log(reversedArr); // Console [5, 4, 3, 2, 1]
- Include
如果数组中存在元素,则此方法返回 true。
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(5)); // true
console.log(arr.includes(10)); // false
- Fill
fill 方法将数组的元素设置为给定值。当我想使用 map/forEach 方法特定次数时,
const emptyArr = new Array(5);
// The problem with this is that you get `[empty x 10]`
// You need real values to map over it.
const filledArr = emptyArr.fill(3); // Console [3, 3, 3, 3, 3]
- At
此方法返回给定索引的元素。这与访问(即 arr[1])元素的传统方式之间的区别在于它也支持负索引。
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(1)); // 2
console.log(arr.at(-1)); // 5
// Important: Negative indices start from `1`, positive indices start from `0`.
- Concat
此方法用于组合两个数组。
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10];
console.log(arr1.concat(arr2)); // Console [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- 删除数组中的重复项
使用 Set 在一行中删除数组中的重复项:
const arr = [...new Set([0, 1, 1, 2, 2])];
console.log(arr);
// arr => [0, 1, 2]
- 没有临时变量的交换变量
let a = 0;
let b = 1;
[a, b] = [b, a];
console.log(a);
// a = 1
console.log(b);
// b = 0
- 在一行中过滤掉所有与 null 相关的值(Nah、undefined、null、")!
const arr = [undefined, null, "", 0, false, NaN, 1, 2, "String"].filter(Boolean);
console.log(arr);
// [ 1, 2, 'String' ]