你的位置:首页 > Java教程

[Java教程]js对象深拷贝


由于引用类型(数组、对象)是按地址传递,直接拷贝是浅拷贝,即修改拷贝后的变量,原变量也会改变。有时需要深拷贝一个对象,这时就需要遍历彻底复制,使原对象和拷贝对象完全脱离关系。

代码:

  function deepCloneObj(obj){    var i;    var o = Array.isArray(obj) ? [] : {};    for(i in obj){      if(obj.hasOwnProperty(i)){        o[i] = typeof obj[i] === "Object"? deepCloneObj(obj[i]) : obj[i];      }    }    return o;  }

实现细节:假定传入的是一个引用类型,首先判定传入的是数组还是对象,根据判定结果,确定o是初始化为空数组还是空对象。之后遍历传入引用类型的自有属性,并判定属性是否为对象,如果是的话做递归,否则直接复制给o。

数组实例:

  var arr1 = ["sfsag","akghak","['fafa','gaag','rwet']",125];  console.log(arr1);//["sfsag", "akghak", "['fafa','gaag','rwet']", 125]  var arr2 = deepCloneObj(arr1);  arr1.push("newstr");  console.log(arr1);//["sfsag", "akghak", "['fafa','gaag','rwet']", 125, "newstr"]  console.log(arr2);//["sfsag", "akghak", "['fafa','gaag','rwet']", 125]

对象实例:

  var obj1 = {sgsh:{sfwg:'ssgsg'},asga:['aff','ghh','wegwer',12],segg:1};  console.log(obj1);//Object {sgsh: Object, asga: Array[4], segg: 1}  var obj2 = deepCloneObj(obj1);  obj1['newstr'] = ['fsg','gsr'];  console.log(obj1);//Object {sgsh: Object, asga: Array[4], segg: 1, newstr: Array[2]}  console.log(obj2);//Object {sgsh: Object, asga: Array[4], segg: 1}