1. JSON方法
let aobj = {
a: 1,
b: "strs",
list: [1, 2, 3],
c: undefined,
d: function () { },
}
const cloneObj = JSON.parse(JSON.stringify(aobj))
2.递归拷贝
function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj
if (obj instanceof Date) return new Date(obj)
if (obj instanceof RegExp) return new RegExp(obj)
if (cache.has(obj)) return cache.get(obj)
let cloneObj = new obj.constructor()
cache.set(obj, cloneObj)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], cache)
}
}
return cloneObj
}
const obj = {
name: 'Jack',
address: {
x: 100,
y: 200
}
}
const newObj = deepClone(obj)