浅拷贝
拷贝一层,如果某个属性值为引用类型,则是共同指向这个引用类型
深拷贝
层层拷贝,深拷贝出来的对象与原对象完全隔离,互不影响
浅拷贝方法
浅拷贝对象的方法:
Object.assign()
拓展运算符
浅拷贝数组的方法:
拓展运算符 slice concat Array.from
深拷贝方法
- 转成JSON格式字符串再parse回来
缺点是
1) 无法正确处理函数
2) 遇到属性值为undefined时 这个属性就直接没了
- 第三方库的方法 如$.extend() 或 lodash.js
- 自定义函数递归实现
function deepClone(inObjet) {
let outObject;
if (typeof inObjet !== 'object' || typeof inObjet === null) {
return inObjet;
}
outObject = Array.isArray(inObjet) ? [] : {};
Object.keys(inObjet).forEach(key => {
let value = inObjet[key];
outObject[key] = deepClone(value);
})
return outObject
}
// 测试一下
const cat = {
name: 'kimi',
age: 12,
foods: ['fish', 'chicken'],
color: {
red: 'red',
blue: 'blue'
},
run() {
console.log('run');
}
}
const dog = deepClone(cat);
dog.foods.push('beef');
dog.color.green = 'green';
console.log(cat);
// age: 12
// color: {red: "red", blue: "blue"}
// foods: (2) ["fish", "chicken"]
// name: "kimi"
// run: ƒ run()
console.log(dog);
// age: 12
// color: {red: "red", blue: "blue", green: "green"}
// foods: (3) ["fish", "chicken", "beef"]
// name: "kimi"
// run: ƒ run()