数组
ES6(ECMAScript 2015)为数组引入了许多新的方法和特性,使得数组操作更加简洁高效。以下是 ES6 中一些重要的数组新特性和方法:
新的数组方法
Array.from()
将类数组对象或可迭代对象(如Set、Map等)转换成一个新数组。
javascript
let divs = document.querySelectorAll("div"); // 类数组对象
let arr = Array.from(divs);
console.log(arr instanceof Array); // 输出: true
// 还可以接受第二个参数,用于映射每个元素
let numbers = Array.from([1, 2, 3], (x) => x + x);
console.log(numbers); // 输出: [2, 4, 6]Array.of()
创建一个包含任意数量参数的新数组,不管参数的数量与类型如何,避免由于单个数值参数而产生的歧义(例如,new Array(5)会创建一个长度为 5 的空数组)。
javascript
let arr = Array.of(7); // 创建一个包含7的数组
console.log(arr); // 输出: [7]
let arrEmpty = Array.of(); // 创建一个空数组
console.log(arrEmpty); // 输出: []find() 和 findIndex()
find(callback[, thisArg]): 返回数组中满足提供的测试函数的第一个元素的值。否则返回undefined。findIndex(callback[, thisArg]): 返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
javascript
let array = [5, 12, 8, 130, 44];
let found = array.find((element) => element > 10);
console.log(found); // 输出: 12
let foundIndex = array.findIndex((element) => element > 10);
console.log(foundIndex); // 输出: 1copyWithin()
在数组内部复制一系列元素到同一数组指定位置,不会改变原数组的长度。
javascript
let array1 = [1, 2, 3, 4, 5];
array1.copyWithin(0, 3); // 从索引3开始复制到索引0的位置
console.log(array1); // 输出: [4, 5, 3, 4, 5]fill()
用静态值填充数组中的元素。
javascript
let array2 = [1, 2, 3, 4, 5];
array2.fill(0, 2, 4); // 从索引2开始到索引4之前填充0
console.log(array2); // 输出: [1, 2, 0, 0, 5]扩展运算符(Spread Operator)
扩展运算符...可以用于展开数组,使其元素成为独立的参数或元素,常用于合并数组、构造函数参数等场景。
javascript
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let merged = [...arr1, ...arr2];
console.log(merged); // 输出: [1, 2, 3, 4, 5, 6]
function myFunction(x, y, z) {}
let args = [0, 1, 2];
myFunction(...args); // 等价于 myFunction(0, 1, 2)解构赋值(Destructuring Assignment)
解构赋值可以从数组中提取值并直接赋给变量。
javascript
let [a, b] = [1, 2];
console.log(a, b); // 输出: 1 2
let [c, , d] = [1, 2, 3];
console.log(c, d); // 输出: 1 3结论
ES6 引入的这些新特性极大地增强了 JavaScript 处理数组的能力,使得代码更加简洁、直观。通过使用这些新方法和语法糖,开发者能够更高效地进行数组操作,同时也提升了代码的可读性和维护性。无论是简单的数据重组还是复杂的数据处理任务,ES6 的数组功能都能提供强有力的支持。