// ...扩展运算符,可以合并数组,合并对象
//1.合并对象
const RNG = {
top: 'letme',
ap: 'xiaohu',
jug: 'mlxg',
ad: 'uzi',
sup: 'xiaoming'
}
//console.log(...RNG); // Uncaught TypeError: Found non-callable @@iterator,对象数组中没有部署迭代器iterator,所以扩展运算符不能够直接操作对象
// 关于迭代器可以参考这篇文章 https://www.cnblogs.com/jony-it/p/10969036.html
const thefullrng = {
...RNG,
anotherTop: 'zitai',
anotherJug: 'karsa',
}
console.log(thefullrng) //top: 'letme', ap: 'xiaohu', jug: 'mlxg', ad: 'uzi', sup: 'xiaoming',anotherTop:'zitai',anotherJug:'karsa'
// 2.合并数组
const IG = ["theshy", 'ningwang', 'rookie', 'jacklove', 'baolan']
console.log(...IG); //theshy ningwang rookie jacklove baolan,此处可以对数组直接进行...操作,是因为数组中部署了Iterator接口
const others = ['duke']
console.log(...IG, ...others); // 合并后的结果为 theshy ningwang rookie jacklove baolan duke
// 注:
// 如果只是一层数组或是对象,其元素只是简单类型的元素,那么属于深拷贝
let aa = {
age: 18,
name: 'aaa'
}
let bb = { ...aa };
bb.age = 22;
console.log(aa.age); // 18
// 如果数组或对象中的元素是引用类型的元素,那么就是浅拷贝
// let personA = {
// age: 18,
// name: 'personA',
// address: {
// city: '成都'
// }
// }
// let personB = { ...personA };
// personB.address.city = '深圳';
// console.log(personA.address.city); // 深圳 此时personA和personB的address.city指向同一个地址,浅拷贝
//可以将上面的浅拷贝变成深拷贝吗?
let personA = {
age: 18,
name: 'personA',
address: {
city: '成都'
}
}
let personB = {
...personA,
address: { ...personA.address } // 如果存在相同的属性,后面的会覆盖前面的
};
personB.address.city = '深圳';
// console.log(personB);
console.log(personB.address.city); // 深圳
console.log(personA.address.city); // 成都