简述汇总ES6中数组新增了哪些扩展?
参考答案:
ES6(ECMAScript 2015)为数组对象引入了一些新的方法和特性,这些扩展主要包括:
- 扩展运算符(Spread Operator):使用
...
语法可以将一个数组展开成多个独立的元素,或者将多个元素合并为一个数组。这可以用于复制数组、合并数组以及函数参数传递等场景。
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const arr3 = [0, ...arr1, 6]; // [0, 1, 2, 3, 6]
- Array.from():这个方法用于从类似数组的对象或可迭代对象创建一个新的数组实例。这允许开发者将类数组对象(如NodeList、arguments对象等)转换为真正的数组。
const nodeList = document.querySelectorAll('div');
const arrayFromNodeList = Array.from(nodeList);
const iterable = {
[Symbol.iterator]() {
let i = 0;
return {
next: () => ({ i, done: i >= 3 }),
return: () => ({ done: true })
};
}
};
const arrayFromIterable = Array.from(iterable); // [0, 1, 2]
- Array.of():这个方法用于创建一个由传入的参数组成的新数组,无论参数的数量或类型。这可以用来替代直接使用字面量创建数组,特别是在参数数量不确定时。
const arr = Array.of(1, 2, '3'); // [1, 2, '3']
- find() 和 findIndex():这两个方法用于在数组中查找满足指定条件的第一个元素及其索引。
find()
方法返回满足条件的元素,而findIndex()
方法返回满足条件的元素的索引。
const arr = [1, 4, 9, 16];
const foundValue = arr.find(value => value > 10); // 9
const foundIndex = arr.findIndex(value => value > 10); // 2
这些新方法和特性使得在JavaScript中处理数组变得更加方便和灵活。