对象中的扩展运算符(…)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
(请认真阅读这句话)
下面为大家举例说明:
1、对象使用扩展运算符
let obj = {a: 1}
let newObj = {...obj}
console.log(newObj) // {a: 1}
// 等价于
let newObj = Object.assign({}, obj)
// 还可以这么用
let obj = {a: 1}
let newObj = {...obj, ...{a:4, b: 2}}
let newObj2 = {...obj, b: 2} // 在redux里经常看到
console.log(newObj) //{ a: 4, b: 2 }
console.log(newObj2) // { a: 1, b: 2 }
需要注意,扩展运算符是浅拷贝,如果遍历的key对应的value是对象就需要注意了
2、数组使用扩展运算符
// 复制数组
let arr =[1,2,3]
let newArr = [...arr]
console.log(newArr) // [1,2,3]
// 可以将数组转换为参数序列
function add(x, y) {
return x + y;
}
const numbers = [1, 2];
add(...numbers) // 3
扩展运算符可以与解构赋值结合起来,用于生成数组
const [first, ...rest] = [1, 2, 3, 4, 5]
first // 1
rest // [2, 3, 4, 5]
需要注意:如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错
const [...rest, last] = [1, 2, 3, 4, 5];
// 报错
const [first, ...rest, last] = [1, 2, 3, 4, 5];
// 报错
3、字符串使用扩展运算符
let str = 'abcdefg'
console.log(...str) // a b c d e f g
let res = ...str // 报错
let arr = [...str] // ['a','b','c','d','e','f','g']
let obj = {...str}
/*{
'0': 'a',
'1': 'b',
'2': 'c',
'3': 'd',
'4': 'e',
'5': 'f',
'6': 'g'
}*/