1つの面接問題は深いコピーと再帰で実現されます(仮想domツリーに似ています)
5101 ワード
実装方法:
再帰
深いコピーの3つの実装方法
1、JSON方法実現
2、for...inで遍歴と複製を実現する
3、配列を利用するArray.prototype.forEach進copy
4、浅いコピー(object.assignメソッドを使用)
再帰
深いコピーの3つの実装方法
1、JSON方法実現
//_tmp result , , 。
let deepClone = function (obj) {
let _tmp = JSON.stringify(obj);// json
let result = JSON.parse(_tmp);// js
return result;
};
let obj1 = {
weiqiujaun: {
age: 20,
class: 1502
},
liuxiaotian: {
age: 21,
class: 1501
}
};
let test = deepClone(obj1);
console.log(test);
2、for...inで遍歴と複製を実現する
function deepClone(obj) {
let result = typeof obj.splice === "function" ? [] : {};
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);// object , deepClone, 。
} else {
result[key] = obj[key];// object , 。
}
}
return result;
}
return obj;
}
let testArray = ["a", "b", "c", "d"];
let testRes = deepClone(testArray);
console.log(testRes);
console.log(typeof testRes[1]);
let testObj = {
name: "weiqiujuan",
sex: "girl",
age: 22,
favorite: "play",
family: {brother: "son", mother: "haha", father: "heihei"}
};
let testRes2 = deepClone(testObj);
testRes2.family.brother = "weibo";
console.log(testRes2);
3、配列を利用するArray.prototype.forEach進copy
let deepClone = function (obj) {
let copy = Object.create(Object.getPrototypeOf(obj));
let propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(function (items) {
let item = Object.getOwnPropertyDescriptor(obj, items);
Object.defineProperty(copy, items, item);
});
return copy;
};
let testObj = {
name: "weiqiujuan",
sex: "girl",
age: 22,
favorite: "play",
family: {brother: "wei", mother: "haha", father: "heihei"}
}
let testRes2 = deepClone(testObj);
console.log(testRes2);
4、浅いコピー(object.assignメソッドを使用)
let target=[];
let testArr=[2,3,5,8];
Object.assign(target,testArr);
console.log(target);
testArr.push(8);
console.log(" "+target+", "+testArr);