深拷貝 方法
- 遍歷對象
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,後面的值會丟失,需要注意,最好用遍歷的方法