ES6 不仅为数组引入了解构赋值,还提供了扩展运算符(Spread Operator)和一系列新的数组方法,使得数组操作更加灵活和高效。本篇将重点介绍这些特性及其用法。
扩展运算符(...)
扩展运算符允许一个数组表达式或字符串在字面量中被展开为多个元素或多个函数参数。
1. 数组中的应用
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
console.log(lyrics); // 输出: ['head', 'shoulders', 'knees', 'and', 'toes']
2. 函数参数中的应用
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 输出: 6
新增的数组方法
ES6 在 Array 对象上新增了多个实用的方法,用于更方便地操作数组。
1. Array.from()
将类数组对象(拥有 length 属性和可索引元素)或可迭代对象(如 Set 和 Map)转换为真正的数组。
let arrayLike = { length: 3, 0: 'a', 1: 'b', 2: 'c' };
console.log(Array.from(arrayLike)); // 输出: ['a', 'b', 'c']
2. Array.of()
创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型。
console.log(Array.of(1, 2, 3)); // 输出: [1, 2, 3]
3. find() 和 findIndex()
find() 方法返回数组中满足提供的测试函数的第一个元素的值。findIndex() 方法返回该元素在数组中的索引。
let array = [1, 4, -5, 10];
console.log(array.find((n) => n < 0)); // 输出: -5
console.log(array.findIndex((n) => n < 0)); // 输出: 2
使用场景
- 扩展运算符:合并数组、将数组元素作为函数参数、复制数组。
Array.from():将类数组对象或集合转换为数组。Array.of():创建具有各种类型元素的数组。find()和findIndex():在数组中查找符合条件的元素或其索引。
注意事项
- 使用扩展运算符时,需要注意目标环境是否支持 ES6。
find()和findIndex()方法在查找不到元素时,find()返回undefined,而findIndex()返回-1。
扩展运算符和新增的数组方法进一步增强了 ES6 对数组的处理能力,使得数组操作更加方便和强大。在下一篇文章中,我们将继续探讨 ES6 中其他关于数组的特性和方法。