ES6 ...运算符的使用

1. 说明

​ 对于...运算符,在不同使用的地方,有不同的叫法。在函数参数处,如果传入的形参个数不确定,那么在定义函数时,形参处使用...运算符定义的参数叫剩余参数;在解构赋值中,使用...运算符叫扩展运算符

2. rest(剩余)参数

// 获取传入参数的和
function getSumOfNums(...nums) {
	// nums是一个数组对象
	console.log(nums instanceof Array) // true
	// 为了方便理解,此处采用for...of结构(可以使用reduce方法,更加简便)
	let total = 0
	for (let item of nums) {
		total += item
	}

	return total
}

console.log(getSumOfNums(1, 2, 3, 4, 5)) // 15

注意:...运算符定义的剩余参数只能放在形参末尾,否则会报错

3. 扩展运算符

// 数组结构中的扩展运算符,得到的是数组(如下nums)
let [num1, num2, ...nums] = [1, 2, 3, 4, 5]
console.log(num1, num2, nums) // 1 2 (3)[3, 4, 5]

// 对象解构中的扩展运算符,得到的是对象(如下others)
let { id, ...others } = { id: '101', name: '张三', sex: '男', age: 30 }
console.log(id, others) // 101 {name: "张三", sex: "男", age: 30}

注意:扩展运算符同样只能放在末尾,否则会报错

原文地址:https://www.cnblogs.com/haveadate/p/13998851.html