Skip to Content

JSON.parse(JSON.stringify(obj)) 只能拷贝普通对象,不能拷贝函数、正则、日期等对象,也不能拷贝对象中的 undefined、Symbol、NaN 等特殊值。具体详见

// const util = require("util"); function deepClone(target, map = new WeakMap()) { if (typeof target !== "object") return target; if (map.has(target)) return map.get(target); // 解决循环引用问题 const res = Array.isArray(target) ? [] : {}; map.set(target, res); for (const key in target) { res[key] = deepClone(target[key], map); } return res; } // 测试 const obj = { foo: { bar: 2, }, list: [1, 2, 3], }; obj.obj = obj; // 循环引用 const obj2 = deepClone(obj); console.log(obj, obj2); // console.log( // util.inspect(obj, { depth: null, colors: true }), // util.inspect(obj2, { depth: null, colors: true }) // ); obj.list[3] = 3333; obj.foo.bar = 3; // console.log( // util.inspect(obj, { depth: null, colors: true }), // util.inspect(obj2, { depth: null, colors: true }) // ); console.log(obj, obj2); // <ref *1> { // foo: { bar: 2 }, // list: [ 1, 2, 3 ], // obj: [Circular *1] // } <ref *1> { // foo: { bar: 2 }, // list: [ 1, 2, 3 ], // obj: [Circular *1] // } // <ref *1> { // foo: { bar: 3 }, // list: [ 1, 2, 3, 3333 ], // obj: [Circular *1] // } <ref *1> { // foo: { bar: 2 }, // list: [ 1, 2, 3 ], // obj: [Circular *1] // }
Last updated on