剩余参数与展开运算符

剩余参数是什么

  1. 认识剩余参数
const add = (x, y, z, ...args) {};
  1. 剩余参数的本质
    剩余参数永远是个数组,即使没有值,也是空数组

剩余参数的注意事项

  1. 箭头函数的剩余参数
    箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号
  2. 使用剩余参数替代 arguments 获取实际参数
  3. 剩余参数的位置
    剩余参数只能是最后一个参数,之后不能再有其他参数,否则会报错

剩余参数的应用

  1. 与解构赋值结合使用
    剩余参数不一定非要作为函数参数使用
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});

数组展开运算符的基本用法

  1. 数组展开运算符的基本用法
console.log(Math.min(...[3, 2, 1]));

数组展开运算符的应用

  1. 复制数组
const a = [1, 2];
const c = [...a];
  1. 合并数组
const a = [1, 2];
const b = [3];
const c = [4, 5];

console.log([...a, ...b, ...c]);
console.log([1, ...a, 2, ...b, ...c, 3]);
  1. 字符串转为数组
    字符串可以按照数组的形式展开
console.log([...'jeck']);
  1. 常见的类数组转化为数组
    arguments
function func () {
	console.log([...arguments]);
}
func(1,2);

NodeList

console.log([...document.querySelector('p')]);

对象展开运算符的基本用法

  1. 展开对象
    把属性罗列出来,用逗号分隔,放到一个 {} 中,构成新对象
const apple = {
	color: '红色',
	shape: '球形',
	taste: '甜'
};
console.log({...apple});
  1. 合并对象
    新对象拥有全部属性,相同属性,后者覆盖前者
const apple = {
	color: '红色',
	shape: '球形',
	taste: '甜'
};
const pen = {
	color: '黑色',
	shape: '圆柱形',
	use: '写字'
}
console.log({...apple, ...pen});

对象展开运算符的注意事项

  1. 空对象的展开
    如果展开一个空对象,则没有任何效果
console.log({...{}});
  1. 非对象的展开
    如果展开的不是对象,则会自动将其转为对象,再将其属性罗列出来
// 以下转换均转为空对象
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]});
  1. 对象中对象属性的展开
    不会展开对象中的对象属性

对象展开运算符的应用

  1. 复制对象
const a = {x: 1, y: 2}
c = {...a}
  1. 用户参数和默认参数
const logUser = userParam => {
	const defaultParam = {
		username: 'ZhangSan',
		age: 0,
		sex: 'male'
	}

	const {username, age, sex} = {...defaultParam, ...userParam}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值