剩余参数是什么
- 认识剩余参数
const add = (x, y, z, ...args) {};
- 剩余参数的本质
剩余参数永远是个数组,即使没有值,也是空数组
剩余参数的注意事项
- 箭头函数的剩余参数
箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号 - 使用剩余参数替代 arguments 获取实际参数
- 剩余参数的位置
剩余参数只能是最后一个参数,之后不能再有其他参数,否则会报错
剩余参数的应用
- 与解构赋值结合使用
剩余参数不一定非要作为函数参数使用
const [num, ...args] = [1, 2, 3, 4];
必须是最后一个
const func = ([num, ...args]) => {};
func([1, 2, 3]);
对象的解构赋值与剩余元素的结合使用
const {x, y, ...z} = {x: 1, y: 2, a: 3, b: 4};
console.log(x, y, z); // 1 2 {a: 3, b: 4}
const func = ({x, y, ...z}) => {};
func({x: 1, y: 2, a: 3, b: 4});
数组展开运算符的基本用法
- 数组展开运算符的基本用法
console.log(Math.min(...[3, 2, 1]));
数组展开运算符的应用
- 复制数组
const a = [1, 2];
const c = [...a];
- 合并数组
const a = [1, 2];
const b = [3];
const c = [4, 5];
console.log([...a, ...b, ...c]);
console.log([1, ...a, 2, ...b, ...c, 3]);
- 字符串转为数组
字符串可以按照数组的形式展开
console.log([...'jeck']);
- 常见的类数组转化为数组
arguments
function func () {
console.log([...arguments]);
}
func(1,2);
NodeList
console.log([...document.querySelector('p')]);
对象展开运算符的基本用法
- 展开对象
把属性罗列出来,用逗号分隔,放到一个 {} 中,构成新对象
const apple = {
color: '红色',
shape: '球形',
taste: '甜'
};
console.log({...apple});
- 合并对象
新对象拥有全部属性,相同属性,后者覆盖前者
const apple = {
color: '红色',
shape: '球形',
taste: '甜'
};
const pen = {
color: '黑色',
shape: '圆柱形',
use: '写字'
}
console.log({...apple, ...pen});
对象展开运算符的注意事项
- 空对象的展开
如果展开一个空对象,则没有任何效果
console.log({...{}});
- 非对象的展开
如果展开的不是对象,则会自动将其转为对象,再将其属性罗列出来
// 以下转换均转为空对象
console.log({ ...1 });
console.log({ ...undefined });
console.log({ ...null });
console.log({ ...true });
如果展开的运算符后面是字符串,它会自动转成一个类似数组的对象,因此返回的不是空对象
console.log({...'name'}); // {0: "n", 1: "a", 2: "m", 3: "e"}
console.log([...'name']); // ["n", "a", "m", "e"]
console.log(...'name'); // n a m e
数组在对象中的展开
console.log({...[1, 2, 3]});
- 对象中对象属性的展开
不会展开对象中的对象属性
对象展开运算符的应用
- 复制对象
const a = {x: 1, y: 2}
c = {...a}
- 用户参数和默认参数
const logUser = userParam => {
const defaultParam = {
username: 'ZhangSan',
age: 0,
sex: 'male'
}
const {username, age, sex} = {...defaultParam, ...userParam}
}