Lol*_*ums 12 javascript clone circular-reference node.js
我从Dmitriy Pichugin 的现有答案中复制了下面的功能.此函数可以深度克隆对象而无需任何循环引用 - 它可以工作.
function deepClone( obj ) {
if( !obj || true == obj ) //this also handles boolean as true and false
return obj;
var objType = typeof( obj );
if( "number" == objType || "string" == objType ) // add your immutables here
return obj;
var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
if( obj instanceof Map )
for( var key of obj.keys() )
result.set( key, deepClone( obj.get( key ) ) );
for( var key in obj )
if( obj.hasOwnProperty( key ) )
result[key] = deepClone( obj[ key ] );
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是,我的程序无限循环,我意识到这是由于循环引用.
循环引用的示例:
function A() {}
function B() {}
var a = new A();
var b = new B();
a.b = b;
b.a = a;
Run Code Online (Sandbox Code Playgroud)
我建议使用Map来映射源中的对象及其在目标中的副本.事实上,我最终WeakMap按照Bergi的建议使用了.每当源对象在映射中时,都会返回其相应的副本,而不是进一步递归.
同时,原始deepClone代码中的一些代码可以进一步优化:
第一部分测试原始值有一个小问题:它的处理方式new Number(1)不同new Number(2).这是因为==第一个if.它应该改为===.但实际上,前几行代码似乎等同于这个测试:Object(obj) !== obj
我还将一些for循环重写为更多功能表达式
这需要ES6支持:
function deepClone(obj, hash = new WeakMap()) {
// Do not try to clone primitives or functions
if (Object(obj) !== obj || obj instanceof Function) return obj;
if (hash.has(obj)) return hash.get(obj); // Cyclic reference
try { // Try to run constructor (without arguments, as we don't know them)
var result = new obj.constructor();
} catch(e) { // Constructor failed, create object without running the constructor
result = Object.create(Object.getPrototypeOf(obj));
}
// Optional: support for some standard constructors (extend as desired)
if (obj instanceof Map)
Array.from(obj, ([key, val]) => result.set(deepClone(key, hash),
deepClone(val, hash)) );
else if (obj instanceof Set)
Array.from(obj, (key) => result.add(deepClone(key, hash)) );
// Register in hash
hash.set(obj, result);
// Clone and assign enumerable own properties recursively
return Object.assign(result, ...Object.keys(obj).map (
key => ({ [key]: deepClone(obj[key], hash) }) ));
}
// Sample data
function A() {}
function B() {}
var a = new A();
var b = new B();
a.b = b;
b.a = a;
// Test it
var c = deepClone(a);
console.log('a' in c.b.a.b); // trueRun Code Online (Sandbox Code Playgroud)
由于对象克隆有很多陷阱(循环引用、原型链、Set/Map 等),
我建议您使用经过充分测试的流行解决方案之一。
比如 lodash 的 _.cloneDeep或'clone' npm module。
| 归档时间: |
|
| 查看次数: |
8107 次 |
| 最近记录: |