...运算符可用于浅拷贝
- 深拷贝
let obj1={name:'Jacl'}
let obj2=obj1
obj1["age"]=12
obj2//{name: "Jacl", age: 12}
用Object.assign(obj)实现深拷贝
let obj1={name:'Jacl'}
let obj2=Object.assign( obj1)
obj1["age"]=12
obj2//{name: "Jacl", age: 12}
- 浅拷贝
let obj1={name:'Jacl'}
let obj2={...obj1}
obj1["age"]=12
obj2//{name: "Jacl"}
当然,我们也可以在浅拷贝的同时修改所获对象的属性
let obj1={name:'Jacl'}
let obj2={...obj1,name:'Zha'}
obj1["age"]=12
obj2//{name: "Zha"}
用Object.assign({}, obj)实现浅拷贝
let obj1={name:'Jacl'}
let obj2=Object.assign({}, obj1)
obj1["age"]=12
obj2//{name: "Jacl"}
数组同理
[...arr1]
- 那么如果想对[{},{},{}...]形式的数据对象进行浅拷贝呢?
...运算符也有其它用处
- 类型转换
set转arr(数组去重)
let s1=new Set([2,1,3,4,3,1])
let arr=[...s1]
arr //[2, 1, 3, 4]
- 获取对象属性/方法
let obj={name:'Li',age:2}
let {name}={...obj}
name//"Li"
- 扩充对象属性(增加数组元素)
let a=[1,2,3]
let b=[4,...a]
b//[4, 1, 2, 3]
let x={name:'Li'};
let y={age:3,...x};
y//{age: 3, name: "Li"}