ES6 (...)展开运算符
Wscats opened this issue · 0 comments
Wscats commented
函数传参
以前我们都是使用Function.prototype.apply方法来将一个数组展开成多个参数,apply 方法的第二个接受一个数组能帮我们把数组展开,然后一一按顺序对应函数的每一个形参,当然如果传进去的数组大于形参个数也是可行的
function test(x, y, z) {
console.log(arguments); //[0, 1, 2]
console.log(x); //0
console.log(y); //1
console.log(z); //2
}
var args = [0, 1, 2];
test.apply(null, args);
test.apply(this, args);
如果我们改用 ES6 的展开运算符就可以这么写了,跟上面的效果一样,但是下面这一种更简洁
function test(x, y, z) {
console.log(arguments);
console.log(x);
console.log(y);
console.log(z);
}
var args = [0, 1, 2];
test(...args);
当然除了展开,还可以支持下面这种,如果我们传递数据,函数形参...items
这种形式,那就是相当于把数据转化为数组,那此时items
形参就是聚合后的数组
'autumn', true, false, 18 => [true, false, 18]
'wscats', 1, 2, 'Hello', ['a', 'b', 'c'] => [1, 2, "Hello", Array[3]]
function test2(type, ...items) {
console.log(items);
}
test2("autumn", true, false, 18);
test2("wscats", 1, 2, "Hello", ["a", "b", "c"]);
当然我们还可以再复杂点,传递多个...arg
function test3(x, y) {
console.log(x); //autumn
console.log(y); //wscats
//...
}
test3(...["autumn"], ...["wscats", 1, 2, "Hello", ["a", "b", "c"]]);
数据解构
其实就是把数组的每个数据拆开然后放进去
let arr = ["autumn", "wscats"];
// 析构数组
let y;
[autumn, ...y] = arr;
console.log(y); // ["wscats"]
数据构造
两个对象连接返回新的对象
let x = {
name: "autumn",
};
let y = {
age: 18,
};
let z = { ...x, ...y };
console.log(z);
两个数组连接返回新的数组
let x = ["autumn"];
let y = ["wscats"];
let z = [...x, ...y];
console.log(z); // ["autumn", "wscats"]
数组加上对象返回新的数组
let x = [
{
name: "autumn",
},
];
let y = {
name: "wscats",
};
let z = [...x, y];
console.log(z);
数组+字符串
let x = ["autumn"];
let y = "wscats";
let z = [...x, y];
console.log(z);
数组+对象
let x = {
name: ["autumn", "wscats"],
age: 18,
};
let y = {
...x, //name: ['autumn','wscats'],age:18
arr: [...x.name], //['autumn','wscats']
};
console.log(y);