📜  ES6 中的数组辅助方法(1)

📅  最后修改于: 2023-12-03 15:14:53.837000             🧑  作者: Mango

ES6 中的数组辅助方法

ES6 中新增加了很多数组方法,这些方法有助于简化开发并提高性能。下面介绍一些常用的数组辅助方法。

Array.from()

该方法用于将类数组或可迭代对象转换成真正的数组。例如,将含有 length 属性且可迭代的字符串转换为数组:

const str = 'hello';
const arr = Array.from(str);
console.log(arr);   // ['h', 'e', 'l', 'l', 'o']
Array.of()

该方法用于创建一个新数组,其参数将作为数组的元素值。该方法相较于传统的构造函数更加便捷:

const arr1 = Array.of(1, 2, 3);
const arr2 = new Array(1, 2, 3);

console.log(arr1);   // [1, 2, 3]
console.log(arr2);   // [1, 2, 3]
Array.prototype.fill()

该方法用于填充一个数组,可以设置开始和结束填充的位置以及填充的值:

const arr = new Array(5);
arr.fill(1, 2, 4);   // 在位置 2 到 3 填充 1
console.log(arr);   // [empty × 2, 1, 1, empty × 1]
Array.prototype.find()

该方法用于返回数组中满足条件的第一个元素,若找不到则返回 undefined:

const arr = [1, 2, 3, 4, 5];
const result = arr.find(item => item % 2 === 0);   // 找到第一个偶数
console.log(result);   // 2
Array.prototype.findIndex()

该方法用于返回数组中满足条件的第一个元素的索引,若找不到则返回 -1:

const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex(item => item % 2 === 0);   // 找到第一个偶数的索引
console.log(index);   // 1
Array.prototype.includes()

该方法用于判断数组中是否包含某个元素,返回 true 或 false:

const arr = [1, 2, 3, 4, 5];
const result1 = arr.includes(2);   // true
const result2 = arr.includes(6);   // false
console.log(result1, result2);
Array.prototype.flat()

该方法用于将嵌套的数组扁平化,使其变为一维数组:

const arr = [1, 2, [3, 4, [5, 6]]];
const result = arr.flat();
console.log(result);   // [1, 2, 3, 4, 5, 6]

这些方法都可以在 ES6 中的数组上进行调用,有助于简化代码并提高效率。