一、剩余参数
1、是什么
(1)认识剩余参数
const add = (x,y,z,...args) => {};
(2)剩余参数的本质
cost add = (x,y,...args) => {
console.log(x,y,args)
};
add(3,4,5,6,7); // 3 4 [5,6,7]
剩余参数永远是个数组,即使没有值,也是空数组。
2、注意事项
(1)箭头函数的剩余参数
箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号。
const add = (…args) => {};
(2)使用剩余参数替代 arguments 获取实际参数
const add = (...args) => {
console.log(args);
};
add(2,3,4,5);
(3)剩余参数的位置
剩余参数只能是最后一个参数,之后不能再有其它参数,否则会报错。
3、应用
(1)完成 add 函数
const add = (...args) => {
let sum = 0;
for(let i = 0; i < args.length; i++){
sum += args[i];
}
return sum;
};
add(2,4,5,6,7);
console.log(sum);
(2)剩余参数与解构赋值结合使用
剩余参数不一定非要作为函数参数使用。
但必须是最后一个
const [num,...args] = [1,2,3,4];
congsole.log(num,args); // 1 [2,3,4]
二、展开运算符
1、数组的展开运算符
(1)基本用法
a、认识展开运算符
[3,1,2] -> 3,1,2
b、基本用法
console.log(Math.min(...[3,1,2]));
// 相当于
console.log(Math.min(3,1,2));
(2)区分剩余参数和展开运算符
a、根本区别
// 展开运算符
[1,2,3] -> 1,2,3
// 剩余参数
1,2,3 -> [1,2,3]
b、区分
// 剩余参数
const add = (...args) =>{
console.log(args);
// 展开运算符
console.log(...args);
};
(3)应用
a、复制数组
const a = [1,2];
const b = [...a];
a[0] = 3;
console.log(a); // [3,2]
console.log(b); // [1,2]
b、合并数组
const a = [1,2];
const b = [3];
const c = [4,5];
console.log(...a,...b,...c); // [1,2,3,4,5]
c、字符串转为数组
console.log([...'alex']); // [a,l,e,x]
d、常见的类数组转化为数组
// arguments
function func(){
console.log([...argumengts]);
}
func(3,4);
// NodeList
console.log([...document.querySelectorAll('p')]);
2、对象的展开运算符
(1)基本用法
a、展开对象
对象不能直接展开,必须在 {} 中展开。
const apple = {
color:'红色',
shape:'球形',
taste:'甜'
};
console.log({...apple});
对象的展开:把属性罗列出来,用逗号分割,放在一个 {} 中,构成新的对象。
b、合并对象
const apple = {
color:'红色',
shape:'球形',
taste:'甜'
};
const pen = {
color:'黑色',
shape:'圆柱形',
use:'写字'
};
console.log({...apple,...pen});
新对象拥有全部属性,相同属性,后者覆盖前者。
(2)注意事项
a、空对象的展开
如果展开一个空对象,则没有任何效果。
console.log({...{}}); // {}
b、非对象的展开
如果展开的不是对象,则会自动将其转为对象,再将其属性罗列出来。
console.log(...1); // {}
console.log(...undefined); // {}
如果展开运算符后面是字符串,它会自动转成一个类似数组的对象,因此返回的不是空对象。
console.log(...'alex'); // {0:'a', 1:'l', 2:'e', 3:'x'}
c、对象中对象属性的展开
不会展开对象中的对象属性。
const apple = {
feature:{
taste:'甜'
}
};
const pen = {
feature:{
color:'黑色',
shape:'圆柱形'
},
use:'写字'
};
console.log({...apple,...pen}); // {feature:{color:'黑色',shape:'圆柱形'},use:'写字'}