- JSON
不支持日期、正则、undefined、函数,环结构
JSON.parse(JSON.stringify(obj))
const cloneDeep = (a, cache) => {
if (!cache) {
cache = new Map(); // 避免全局变量,仅第一次拷贝创建
}
if (cache.get(a)) { // 避免环
return cache.get(a)
}
if (a instanceof Object) { // 不考虑 iframe
let result = undefined;
if (a instanceof Function) {
if (a.prototype) { // a 存在 prototype,代表 a 是普通函数
result = function () {
return a.apply(this, arguments)
}
} else {
result = (...args) => a.call(undefined, ...args);
}
}
else if (a instanceof Array) {
result = []
}
else if (a instanceof Date) {
result = new Date(a - 0)
}
else if (a instanceof RegExp) {
result = new RegExp(a.source, a.flags)
} else {
result = {}
}
cache.set(a, result)
for (let k in a) {
if (a.hasOwnProperty(k)) { // 仅遍历自身属性
result[k] = cloneDeep(a[k], cache)
}
}
return result
} else {
return a
}
}
const a = {
name: 'xm',
say: function () {
console.log('say');
},
hi: () => console.log('hi'),
bir: new Date(),
reg: /123/,
family: ['xh', 'xg']
}
a.self = a
const b = cloneDeep(a)