javascript对象的深度克隆/复制
Deep cloning/copy for javascript objects
在寻找深度复制包含嵌套和循环结构的对象的方法时,在循环引用和原型继承方面,这两种方法(1、2、3、4)都没有完美的解决方案。
我在这里编写了自己的实现。它能很好地完成任务还是算是一个更好的解决方案?
/*
a function for deep cloning objects that contains other nested objects and circular structures.
objects are stored in a 3D array, according to their length (number of properties) and their depth in the original object.
index (z)
|
|
|
|
|
| depth (x)
|_ _ _ _ _ _ _ _ _ _ _ _
/_/_/_/_/_/_/_/_/_/
/_/_/_/_/_/_/_/_/_/
/_/_/_/_/_/_/...../
/................./
/..... /
/ /
/------------------
object length (y) /
*/
function deepClone(obj) {
var i = -1, //depth of the current object relative to the passed 'obj'
j = 0; //number of the object's properties
var arr = new Array(); //3D array to store the references to objects
return clone(obj, arr, i, j);
}
function clone(obj, arr, i ,j){
if (typeof obj !== "object") {
return obj;
}
var result = Object.create(Object.getPrototypeOf(obj)); //inherit the prototype of the original object
if(result instanceof Array){
result.length = Object.keys(obj).length;
}
i++; //depth is increased because we entered an object here
j = Object.keys(obj).length; //native method to get the number of properties in 'obj'
arr[i] = new Array(); //this is the x-axis, each index here is the depth
arr[i][j] = new Array(); //this is the y-axis, each index is the length of the object (aka number of props)
//start the depth at current and go down, cyclic structures won't form on depths more than the current one
for(var depth = i; depth >= 0; depth--){
//loop only if the array at this depth and length already have elements
if(arr[depth][j]){
for(var index = 0; index < arr[depth][j].length; index++){
if(obj === arr[depth][j][index]){
return obj;
}
}
}
}
arr[i][j].push(obj); //store the object in the array at the current depth and length
for (var prop in obj) {
result[prop] = clone(obj[prop], arr, i, j);
}
return result;
}
你能试试下面的简单逻辑吗。将js对象转换为新的String,然后再次转换为对象。
例如:
var car = {type:"Fiat", model:"500", color:"white"};
var cloneStr = new String(JSON.stringify(car));
var carClone = JSON.parse(cloneStr);
carClone.type = "Maruthi";
alert(JSON.stringify(car)) ;
alert(JSON.stringify(carClone)) ;
相关文章:
- 使用Clipboard.js复制span文本
- ZeroClipboard-在复制之前添加到值
- 如何对映射插件创建的敲除对象进行深度复制
- NodeJS中的高效深度复制
- javascript中嵌套对象的深度复制数组
- lodash:深度复制对象,但不是所有属性
- 用javascript将一个对象数组复制到另一个数组中(深度复制)
- 在 Angular 2 + TypeScript 中深度复制数组
- 在 Javascript 中,在执行深度复制时,由于属性为“this”,我如何避免循环
- Angular.copy() 不是深度复制引用的数组
- javascript对象的深度克隆/复制
- 如何防止jQuery扩展深度副本复制我的一些自定义属性
- Ecma6,Object.assign 不做深度复制
- 结构化克隆算法与深度复制算法有何不同?
- 如何在javascript中深度复制对象作为对象而不是数组
- 如何在深度复制时深层复制闭合对象(私有对象)
- 如何在JavaScript中深度复制自定义对象
- 如何在javascript中进行深度复制
- 使用 Array.prototype.slice() 深度复制数组
- 深度复制可观察数组