1. 程式人生 > >JS物件陣列的深度拷貝

JS物件陣列的深度拷貝

直接=是淺拷貝,對於想完全複製可以這樣:

途徑1  let arrObj2=JSON.parse(JSON.stringify(arrObj1));

途徑2 

var objDeepCopy = function (source) {     var sourceCopy = source instanceof Array ? [] : {};     for (var item in source) {         sourceCopy[item] = typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item];     }     return sourceCopy; } var objCopy = objDeepCopy(obj); objCopy[0].a.a1[1] = "a13"; objCopy[1][1].e = "6"; obj   // => [{ "a": { "a1": ["a11", "a12"], "a2": 1 }, "b": 2 }, ["c", { "d": 4, "e": 5 }]] objCopy   // => [{ "a": { "a1": ["a11", "a13"], "a2": 1 }, "b": 2 }, ["c", { "d": 4, "e": 6 }]]