深拷贝 方法
- 遍历对象
function deepCopy(obj) {
let newObj = Array.isArray(obj) ? [] : {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof obj[i] === "object") {
if (obj[i] === null) {
newObj[i] = null;
} else {
newObj[i] = deepCopy(obj[i]);
}
} else {
newObj[i] = obj[i];
}
}
}
return newObj;
}
let obj = {
name: "张三",
age: 20,
arr: [1, 2, 3],
obj3: {
},
test: undefined,
fn: function () {
console.log("fn...");
},
test2: null
}
let obj2 = deepCopy(obj);
- 用 json.stringify 方法
let obj2 = JSON.parse(JSON.stringify(obj));
JSON.stringify 方法 会产生一个新的对象,但是这个方法,如果遇到 undefined,后面的值会丢失,需要注意,最好用遍历的方法