浅拷贝和深拷贝
引用关系
深拷贝: 拷贝后的结果不影响之前的,前后无关系,浅拷贝则相反。
… 只能拷贝一层
slice()
JSON.parse(),JSON.stringify()
- 函数丢失、undefined
无法实现复杂的拷贝
function deepCopy(obj, hash = new WeakMap()) {
if (obj == null) return obj;
if (obj instanceof RegExp) return new RegExp(obj);
if (obj instanceof Date) return new Date(obj);
if (typeof obj !== "object") return obj;
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
hash.set(obj, cloneObj);
for (const key in obj) {
if (Object.hasOwnProperty(key)) {
cloneObj[key] = deepCopy(obj[key]);
}
}
return cloneObj;
}