深层次递归方式
function deepClone(baseObj) {
if (typeof baseObj !== "object") return;
let newObj = baseObj instanceof Array ? [] : {};
for (let key in baseObj) {
if (baseObj.hasOwnProperty(key)) {
// 如果原型对象中的key属性存在,进入下一轮
const el = baseObj[key];
if (el instanceof Date) {
newObj[key] = new Date(el);
} else if (el instanceof RegExp) {
newObj[key] = new RegExp(el);
} else if (el instanceof HTMLElement) {
const dom = document.getElementByTagName(el.nodeName)[0];
newObj[key] = dom.cloneNode(true);
} else {
newObj[key] = typeof el === "object" ? deepClone(el) : el;
}
}
}
return newObj;
}
let obj1 = { a: 1, b: 2, c: [[1], 2] };
let obj2 = deepClone(obj1);
obj1.a = 3;
obj2.c[0][0] = 2;
JS深度克隆(深拷贝)
最新推荐文章于 2023-05-28 22:50:59 发布