1、定义
扩展运算符(spread)是三个点(…),它如同rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。
2、使用
console.log(...[1,2,3]); //1 2 3
console.log(1,...[2,3,4],5); // 1 2 3 4 5
console.log(0,...[1,2,3,[4,5]],6); //0 1 2 3 [ 4, 5 ] 6
该运算符主要用于函数调用。
function add(x,y){
return x + y;
}
let numbers = [4,38];
add(...numbers); // 42
扩展运算符与正常的函数参数可以结合使用,非常灵活。
function f(v,w,x,y,z){
console.log(v,w,x,y,z)
};
let args = [0,1];
f(-1,...args,2,...[3]); //-1 0 1 2 3
扩展运算符后面还可以放置表达式:
const arr = [...(x > 0 ? ['a'] : []),'b'];
如果扩展运算符后面是一个空数组,则不产生任何效果:
[...[],1]; //[1]
坚持写博第2/100天