浅拷贝
1 直接赋值
2 扩展运算符(...)
3 abject.assign()
Object.assign({}, obj);
4 slice和concat
slice 截取数组
concat 拼接数组
深拷贝
1 JSON.parse(JSON.stringify(待拷贝对象))
2 使用第三方库 Lodash
javascript
const _ = require('lodash');
let obj = {
name: 'demo',
age: 26
}
let obj2 = _.cloneDeep(obj);
obj2.name = "demo_new";
console.log(obj); // {name: "demo", age: 26}
console.log(obj2); // {name: "demo_new", age: 26}
3 手写一个深拷贝
javascript
function deepClone (obj) {
if (typeof obj !== 'object' || obj == null) {
return obj;
}
let deepCloneObj = Array.isArray(obj) ? [] : {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
deepCloneObj[key] = deepClone(obj[key]);
}
}
return deepCloneObj;
}