- JSON.stringify 的问题
- 三个点和 Object.assign 都是浅拷贝
它们都是用来进行浅拷贝的,好的地方是能拷贝 undefined、函数、Symbol、正则...
- 自己实现深拷贝:递归浅拷贝
const copy = (target) => {
const type = Object.prototype.toString.call(target)
if (/(regexp|date)/i.test(type)) return new target.constructor(target)
if (/error/i.test(type)) return new target.constructor(target.message)
if (/function/i.test(type)) return new Function('return ' + target.toString())()
if (target === null || typeof target !== 'object') return target
const result = new target.constructor()
for (const attr in target) {
result[attr] = copy(target[attr])
}
return result
}
- 如何循环引用
const copy = (target, m = new Map()) => {
const type = Object.prototype.toString.call(target)
if (/(regexp|date)/i.test(type)) return new target.constructor(target)
if (/error/i.test(type)) return new target.constructor(target.message)
if (/function/i.test(type)) return new Function('return ' + target.toString())()
if (target === null || typeof target !== 'object') return target
if (m.get(target)) return m.get(target)
const result = new target.constructor()
m.set(target, result)
for (const attr in target) {
result[attr] = copy(target[attr], m)
}
return result
};
- 实际我怎么做的
const o = _.cloneDeep(obj1)