随着前端技术的不断发展,ES6(ECMAScript 6)成为了前端开发者必须掌握的一种技术。在 ES6 中,新增了很多让我们开发变得更加高效的功能,其中就包括 6 种数组扩展方法。这些方法可以使我们的代码更加优雅和简洁。下面我们来一一解读这些数组扩展方法。
1. Array.from()
Array.from() 方法从一个类数组或可迭代对象中创建一个新的数组实例。和 Array.prototype.slice.call() 的作用是一样的,但是更加语义化和方便使用。
示例代码:
// www.javascriptcn.com code example
const arrLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
const arr1 = Array.prototype.slice.call(arrLike); // 使用 call 转换
console.log(arr1); // ['a', 'b', 'c']
const arr2 = Array.from(arrLike); // 使用 Array.from()
console.log(arr2); // ['a', 'b', 'c']2. Array.of()
Array.of() 方法创建一个包含任意数量参数的新数组实例。和 Array() 构造函数作用是一样的,但是区别在于当只传入一个参数时,Array() 表示的是数组的长度,并不是实际的数组元素。
示例代码:
// www.javascriptcn.com code example const arr1 = new Array(3); // 创建一个长度为 3 的空数组 console.log(arr1); // [empty × 3] const arr2 = Array(3); // 同上 console.log(arr2); // [empty × 3] const arr3 = Array.of(3); // 创建一个包含元素 3 的数组 console.log(arr3); // [3] const arr4 = Array.of(1, 2, 3); // 创建一个包含元素 1、2、3 的数组 console.log(arr4); // [1, 2, 3]
3. Array.prototype.fill()
Array.prototype.fill() 方法填充一个数组的所有元素,从起始索引到终止索引,并使用给定的值进行替换。如果省略终止索引,则默认为数组的末尾。
示例代码:
const arr = new Array(3).fill(0); // 填充数组 console.log(arr); // [0, 0, 0] const arr2 = [1, 2, 3]; arr2.fill(0, 1, 2); // 从索引 1 开始填充,到索引 2 停止 console.log(arr2); // [1, 0, 3]
4. Array.prototype.find()
Array.prototype.find() 方法返回数组中第一个满足条件的元素,如果不存在则返回 undefined。
示例代码:
const arr = [1, 2, 3, 4, 5]; const num = arr.find(item => item > 2); // 找到第一个大于 2 的元素 console.log(num); // 3 const num2 = arr.find(item => item > 6); // 找不到满足条件的元素 console.log(num2); // undefined
5. Array.prototype.findIndex()
Array.prototype.findIndex() 方法返回数组中第一个满足条件的元素的索引,如果不存在则返回 -1。
示例代码:
const arr = [1, 2, 3, 4, 5]; const index = arr.findIndex(item => item > 2); // 找到第一个大于 2 的元素索引 console.log(index); // 2 const index2 = arr.findIndex(item => item > 6); // 找不到满足条件的元素 console.log(index2); // -1
6. Array.prototype.includes()
Array.prototype.includes() 方法判断一个数组中是否包含指定的值,返回 true 或 false。
示例代码:
const arr = [1, 2, 3]; const hasNum = arr.includes(2); // 数组中包含 2 console.log(hasNum); // true const notHasNum = arr.includes(4); // 数组中不包含 4 console.log(notHasNum); // false
以上就是 ES6 中的 6 种数组扩展方法的详细解读及使用技巧。通过使用这些方法,我们可以使代码更加简洁和优雅。在日常开发中,可以根据具体的业务场景灵活选择使用哪种方法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c8dc6be46428fe9efabc4f