扩展
运算符
是三个点(…),好比rest参数的逆运算,讲一个数组转为用逗号分隔的参数序列
console.log(...[1, 2, 3]); //1 2 3
console.log(1,...[2,3,4],5); //1 2 3 4 5
console.log([...document.querySelectorAll('div')]); //[div, div, div]
# 将一个数组变为参数序列
function push(array, ...items){
array.push(...items);
return array;
}
var arr = [1,3];
console.log(push(arr, 1, 3, 4)); //[ 1, 3, 1, 3, 4 ]
function add(x, y) {
return x + y;
}
var number = [4,38];
console.log(add(...number)) //42
# 替代数组的apply的方法
//es5
function f(x,y,z) {}
var arr = [0,1,2];
f.apply(null,arr);
//es6
f(...arr);
#使用Math简化数组取最大值
console.log(Math.max.apply(null, [14, 3, 7])); //14
console.log(Math.max(...[14, 3, 7])); //14
# push函数将一个数组添加到另一个数组尾部(亲测不行)
var arr1=[0,1,2];
var arr2 =[3,4,5];
console.log(Array.prototype.push.apply(arr1, arr2)); //亲测: 6,并未像文中所说的将一个数组追加到另一个数组尾部
console.log(arr1.concat(arr2)); //[ 0, 1, 2, 3, 4, 5 ]
console.log(arr1.push(...arr2)); // 亲测: 6, 并未像文中所说的将一个数组追加到另一个数组尾部
console.log(new (Date.bind.apply(Date, [null, 2015, 1, 1]))); //2015-01-31T16:00:00.000Z
console.log(new Date(...[2015, 1, 1])); //2015-01-31T16:00:00.000Z
# 合并数组
var arr1=[0,1,2];
var arr2 =[3,4,5];
arr1 = arr1.concat(arr2);
console.log(arr1); //[ 0, 1, 2, 3, 4, 5 ]
console.log([...arr1, ...arr2]);//[ 0, 1, 2, 3, 4, 5 ]
#与解构赋值结合
const [frist, ...rest] = [1,2,3,4,5,6];
console.log(frist); //1
console.log(rest);//[ 2, 3, 4, 5, 6 ]
const [frist, ...rest] = [];
console.log(frist); //undefined
console.log(rest);//[]
const [frist, ...rest] = ["foo"];
console.log(frist); //foo
console.log(rest);//[]
# 类似数组的对象 - Map和Set结构
let map = new Map([
[1,'one'],
[2,'two'],
[3,'three']
])
let arr = [...map.keys()]; //[ 1, 2, 3 ]
# 类似数组的对象 - Generator函数
var go = function *() {
yield 1;
yield 2;
yield 3;
}
[...go()]; //[1,2,3]
ps:如果没有对iterator接口的对象使用扩展运算符,将会报错