经常遇到对数组的操作…下面是《ES6标准入门》(第3版)中对数组扩展的(部分)描述:
扩展运算符(…):
console.log(...[1,2,3])
// 1 2 3console.log(1, ... [2,3,4], 5)
// 1 2 3 4 5
扩展运算符代替数组的apply方法
// ES5
function f(x,y,z) {// ...
}
var args = [1,2,3];
f.apply(null, args);// ES6
function f(x,y,z) {// ...
}
var args = [0,1,2]
f(...args);// 可见,调用更清晰
Math.max
// ES5
Math.max.apply(null, [14, 3, 77])// ES6
Math.max(...[14, 3, 77])// 等同于
Math.max(14, 3, 77)
合并数组:
// ES5
var arr1 = [0,1,2];
var arr2 = [3,4,5];
Array.prototype.push.apply(arr1, arr2);// ES6
const arr1 = [0,1,2];
const arr2 = [3,4,5];
arr1.push(...arr2);
与解构赋值结合使用:
// ES5
a = list[0], rest = list.slice(1)// ES6
[a, ...rest] = list
将字符串转换成真正的数组:
const str = 'hello';
const arr = [...str];
Map
const map = new Map([[1, 'one'],[2, 'two'],[3, 'three']
])
const keys = [...map.keys()]; // [1, 2, 3]
const values = [...map.values()]; // ["one", "two", "three"]