js深拷贝
1.js深拷贝
function deepClone(obj, hash = new Map()) {
if (!obj || typeof obj != "object") return obj;
if (hash.get(obj)) return hash.get(obj);
let cloneObj = Array.isArray(obj) ? [] : {};
hash.set(obj, cloneObj);
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
obj[i] = deepClone(obj[i], hash);
}
}
return obj;
}
let a = [1, 2, 3, 4, { name: "栋dong", age: 20, speak: () => { console.log("我好牛逼") }, array: [0, 8, 1, 4] }];
b = deepClone(a);
console.log(b)
//**********处理更多
function deepCopy(data, hash = new WeakMap()) {
if(typeof data !== 'object' || data === null){
throw new TypeError('传入参数不是对象')
}
// 判断传入的待拷贝对象的引用是否存在于hash中
if(hash.has(data)) {
return hash.get(data)
}
let newData = {};
const dataKeys = Object.keys(data);
dataKeys.forEach(value => {
const currentDataValue = data[value];
// 基本数据类型的值和函数直接赋值拷贝
if (typeof currentDataValue !== "object" || currentDataValue === null) {
newData[value] = currentDataValue;
} else if (Array.isArray(currentDataValue)) {
// 实现数组的深拷贝
newData[value] = [...currentDataValue];
} else if (currentDataValue instanceof Set) {
// 实现set数据的深拷贝
newData[value] = new Set([...currentDataValue]);
} else if (currentDataValue instanceof Map) {
// 实现map数据的深拷贝
newData[value] = new Map([...currentDataValue]);
} else {
// 将这个待拷贝对象的引用存于hash中
hash.set(data,data)
// 普通对象则递归赋值
newData[value] = deepCopy(currentDataValue, hash);
}
});
return newData;
}
本文作者:yang10086
本文链接:https://www.cnblogs.com/yang10086/p/17025002.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步