扩展运算符(spread)是三个点(...)
数组的扩展运算符
将一个数组转为用逗号分隔的参数序列
1. 用于函数调用:
function add(x, y) {
return x + y;
}
const numbers = [2, 3];
add(...numbers) // 5
2. 求最大值
Math.max(...[11, 6, 22])
// 22
3. 复制数组
const arr1 = [1,2]
// 方法1
// const arr2 = [...arr1]
// 方法2
const [...arr2] = arr1
console.log(arr1) // [1, 2]
console.log(arr2) // [1, 2]
// 上面的两种写法,arr2都是arr1的克隆。
4. 合并数组(多个)【浅拷贝】
// 合并数组
const arr1 = ['a', 'b']
const arr2 = ['c', 'd']
const arr3 = ['e']
const arr4 = [...arr1, ...arr2, ...arr3]
console.log(arr4)
// [ 'a', 'b', 'c', 'd', 'e' ]
5. 与解构赋值结合
如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。
let arr = [1, 2, 3, 4, 5]
let [num1, ...num2] = arr
console.log(num2) // [ 2, 3, 4, 5 ]
6. 字符串
扩展运算符还可以将字符串转为真正的数组。
const name = 'vivo'
console.log([...name])
// [ 'v', 'i', 'v', 'o' ]
对象的扩展运算符
使用...可以将对象中所有的属性给当前对象添加一份
let obj = {
name: '华为',
age: 30,
say () {
console.log(this.name,this.age)
}
}
// 使用...可以将对象中所有的属性给当前对象添加一份!
let objSupper = {
...obj,
text: '华而有为'
}
console.log(objSupper)
// { name: '华为', age: 30, say: [Function: say], text: '华而有为' }