- JSON.parse(JSON.stringify(obj))
- 递归拷贝
function checkType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
function deepClone(obj) {
if (typeof obj !== "object") {
return obj
}
let targetType = checkType(obj);
let result = targetType === "Object" ? {} : [];
if (targetType === "Array") {
for (const [key, value] of obj.entries()) {
let itemType = checkType(value)
if (itemType === "Object" || itemType === "Array") {
result[key] = deepClone(value)
} else {
result[key] = value;
}
}
} else {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const item = obj[key];
let itemType = checkType(item);
if (itemType === "Object" || itemType === "Array") {
result[key] = deepClone(item)
}else{
result[key] = item;
}
}
}
}
return result
}
let obj = {
a: 1,
b: [1, 23, 45, {
d: '你好',
e: null,
f: undefined
}],
c: {
d: '你好',
e: null,
f: undefined
},
h(){
console.log('你好')
}
}
let newobj = deepClone(obj)
console.log(newobj)
newobj.h()
- Object.assign(newobj,obj)
- let cloneObj = {…obj}
- let cloneArr = oldArr.slice(0)