經常遇到對數組的操作…下面是《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"]