... 展开运算符 (作用:数组与参数的相互转换)
用于函数调用
1.将数组转为参数
function filter1(type,x,y){
console.log(x)//true
console.log(y)//0
}
let items=[true, 0,false]
filter1('boolean',...items);
2.将参数或iterable转为数组
iterable是ES6标准引入的新的类型。而Array、Map和Set都属于iterable类型
function filter1(type,...items){
console.log(items)// [true, 0,false]
}
filter1('boolean',true,0,false);
例子:
1.
function push(array, ...items) {
// var arr =[2,3]
// arr.push(1,5,7)
//console.log(arr) //[2, 3, 1, 5, 7]
array.push(...items);
}push([],4,7,9) //[4,7,9]
2.数组自由合并(将数组转为参数)
var iterableObj = ["第一个","first"]
var arr = [...iterableObj, 4, 5, 6]
console.log(arr) // ["第一个", "first", 4, 5, 6]
function a(a,b,c,d){
console.log(arguments)
console.log(a)//[1, Array(2), 4]
console.log(b)//5
console.log(c)//6
console.log(d)//[7]
}
var arr = [
[1,[2,3],4],
5,6,[7]
]
a(...arr)
ES5
目前为止,我们都是使用Function.prototype.apply方法来将一个数组展开成多个参数:
function myFunction(x, y, z){ }
varargs = [0,1,2];
myFunction.apply(null, args);
使用es6的展开运算符可以这么写:
function myFunction(x, y, z){ }
varargs = [0,1,2];
myFunction(...args);
选择性传参
function filterPara(type, ...items){
console.log(items) //[false,4,'Welcome',7]
return items.filter(item=>
typeof item === type
);
}
filterPara('number',false,4,'Welcome',7);// => [4, 7]
数据解构
let cold = ['autumn', 'winter','spring', 'summer'];
let otherSeasons, autumn;
[autumn, ...otherSeasons] = cold;
otherSeasons// ["winter", "spring", "summer"]
数据构造
两个对象连接返回新的对象
let a = {aa:'aa'}
let b = {bb:'bb'}
let c = {a,b}
console.log(c) //{a: {aa:'aa'}, b: {bb:'bb'}}
let a = {aa:'aa'}
let b = {bb:'bb'}
let c = {...a,...b}
console.log(c) // {aa: "aa", bb: "bb"}
网友评论