1.当用户想要输入的参数不确定时,就可以用剩余参数来表示
const add = (x,y,z,...args) =>{};
2.剩余参数的本质
const add = (x, y, ...args) => {
console.log(x, y, args);
};
add(); //undefined undefined
add(1); //1 undefined
add(1, 2); // 1 2 []
add(1, 2, 3); // 1 2 [3]
结论:剩余参数永远是个数组,即使没有值,也是空数组
3.箭头函数的参数即使只有一个剩余参数,也不能省圆括号
4.使用箭头函数替代arguments获取实际参数
```
const sub = function() {
console.log(arguments);
}
sub(); //Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
sub(1, 2, 3); //Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// 比较
const subbb = (...args) => {
console.log(args); //[1,2]直接是个数组,可以用数组的方法
};
subbb(1, 2);
```
5.剩余参数在实际中的应用
//完成add()函数
const addDemo = (...argss) => {
let sum = 0;
for (let i = 0; i < argss.length; i++) {
sum += argss[i];
}
return sum;
};
console.log(addDemo()); //0
console.log(addDemo(1, 2, 3, 4)); //10
6.剩余参数和解构赋值结合使用
const [kkk, ...argsd] = [1, 2, 3, 43, 4];
console.log(kkk, argsd); //1 (4) [2, 3, 43, 4]
7.数组的展开运算符
console.log(...[2, 2, 2, 2]); // 2 2 2 2
console.log(Math.min(...[3, 2, 1])); // 1
8.数组展开运算符的应用
//复制数组
const a = [1, 3, 7];
const c = [...a];
console.log(c); //(3) [1, 3, 7]
//合并数组
const b = [1, 2];
const f = [3, 4];
const r = [...b, ...f]
console.log(r); //(4) [1, 2, 3, 4]
//字符串转为数组
console.log(...
'alexx'); //a l e x x
console.log([...
'alexxnb' //(7) ['a', 'l', 'e', 'x', 'x', 'n', 'b']
]);
9.对象的展开运算符
9.1.展开对象:对象不能直接展开,必须在{}中展开
const apple = {
color: '红色',
shape: '球形',
taste: '甜'
};
console.log({...apple
}); //新对象,{color: '红色', shape: '球形', taste: '甜'}
9.2合并对象:新对象拥有全部属性,相同属性,后者覆盖前者
const lizi = {
color: 'bai色',
shape: '球形',
taste: '甜'
};
const shizi = {
color: '黄色',
shape: '椭圆形',
taste: '甜'
};
console.log({...lizi,
...shizi
}); //{color: '黄色', shape: '椭圆形', taste: '甜'}
9.3对象展开运算符的作用
const obj1 = {
username: 'www',
password: 'wwws',
sayHEHE: () => {
console.log(呵呵);
}
}
const {
obj2
} = {
...obj1
}
console.log(obj1 === obj2); //false