复杂数组以及对象的深度拷贝

xiaoxiao2021-02-28  18

//测试用例 var obj = { name: "ceshi", age: 12, list: [{ name: "ceshi2", age: 13 }, { name: "ceshi3", age: 14 }] };

方法一:利用JSON

var str=JSON.stringify(obj); //验证 obj.list[0].name="new123"; var newObj=JSON.parse(str);

方法二:递归

function clone(obj){ var newObj; //数组类型的拷贝 if (obj instanceof Array) { newObj=[]; var i=obj.length; while(i--){ newObj[i]=clone(obj[i]); } return newObj; } //对象类型的拷贝 else if(obj instanceof Object){ newObj={}; for (var k in obj) { newObj[k]=clone(obj[k]); } return newObj; } else { return obj; } } var newObj=clone(obj); obj.list[0].name="OK"; alert(obj);
转载请注明原文地址: https://www.6miu.com/read-1650172.html

最新回复(0)