对象的扩展运算符(...),用于取出参数对象中的所有可遍历属性,然后拷贝到当前对象之中
对象扩展运算符:
1. 复制对象
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { ...obj1 }
obj2 = { x: 1, y: 2, z: 3 }
2. 合并对象
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { x: 4, y: 5, z: 6 }
let obj3 = { ...obj1, ...obj2 }
obj3 = { x: 1, y: 2, z: 3, x: 4, y: 5, z: 6 }
3. 自定义属性
let obj1 = { x: 1, y: 2, z: 3 }
let obj2 = { ...obj1, a: 4, b: 5, c: 6 }
obj2 = { x: 1, y: 2, z: 3, a: 4, b: 5, c: 6 }
注意:若自定义属性在扩展运算符的后面,且与扩展运算符内的属性同名,则扩展运算符内的属性会被覆盖掉
数组扩展运算符
1. 复制数组
let arr1 = [1, 2, 3]
let arr2 = [ ...arr1 ]
arr2 = [1, 2, 3]
2. 合并数组
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [ ...arr1, ...arr2 ]
arr3 = [1, 2, 3, 4, 5, 6]
3. 字符串变数组
let arr1 = [1, 2, 3]
let str1 = 'hello'
let arr2 = [...arr1, ...str1]
arr2 = [ 1, 2, 3, "h", "e", "l", "l", "o" ]