ES6 为数组新增了一些非常有用的 API,这些 API 提高了数组操作的便利性和效率。以下是 ES6 给数组新增的主要 API 及其详细解释和示例:
1. Array.from()
Array.from()
方法从类数组对象或可迭代对象创建一个新的数组实例。
const arrayLike = {0: 'a',1: 'b',2: 'c',length: 3
};
const arr = Array.from(arrayLike);
console.log(arr); // 输出: ['a', 'b', 'c']const set = new Set(['a', 'b', 'c']);
const arrFromSet = Array.from(set);
console.log(arrFromSet); // 输出: ['a', 'b', 'c']
2. Array.of()
Array.of()
方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。
const arr1 = Array.of(1, 2, 3);
console.log(arr1); // 输出: [1, 2, 3]const arr2 = Array.of(7);
console.log(arr2); // 输出: [7]
3. Array.prototype.find()
find()
方法返回数组中满足提供的测试函数的第一个元素的值。如果没有找到满足条件的元素,则返回 undefined
。
const array = [5, 12, 8, 130, 44];
const found = array.find(element => element > 10);
console.log(found); // 输出: 12
4. Array.prototype.findIndex()
findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。如果没有找到满足条件的元素,则返回 -1
。
const array = [5, 12, 8, 130, 44];
const index = array.findIndex(element => element > 10);
console.log(index); // 输出: 1
5. Array.prototype.fill()
fill()
方法用一个固定值填充数组中从起始索引到终止索引的全部元素。
const array = [1, 2, 3, 4, 5];
array.fill(0, 2, 4);
console.log(array); // 输出: [1, 2, 0, 0, 5]
6. Array.prototype.copyWithin()
copyWithin()
方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,而不修改其大小。
const array = [1, 2, 3, 4, 5];
array.copyWithin(0, 3);
console.log(array); // 输出: [4, 5, 3, 4, 5]
7. Array.prototype.entries()
entries()
方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。
const array = ['a', 'b', 'c'];
const iterator = array.entries();for (const [index, value] of iterator) {console.log(index, value); // 输出: 0 'a', 1 'b', 2 'c'
}
8. Array.prototype.keys()
keys()
方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键。
const array = ['a', 'b', 'c'];
const iterator = array.keys();for (const key of iterator) {console.log(key); // 输出: 0, 1, 2
}
9. Array.prototype.values()
values()
方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的值。
const array = ['a', 'b', 'c'];
const iterator = array.values();for (const value of iterator) {console.log(value); // 输出: 'a', 'b', 'c'
}
10. Array.prototype.includes()
includes()
方法用来判断一个数组是否包含一个指定的值,如果是返回 true
,否则返回 false
。
const array = [1, 2, 3];
console.log(array.includes(2)); // 输出: true
console.log(array.includes(4)); // 输出: false
总结
ES6 为数组新增的这些 API 提供了更强大和简洁的操作方式,使得数组操作更加方便和直观。通过利用这些新特性,开发者可以编写出更加简洁、高效和可读的代码。