2016-06-20 52 views
2

我想分配一個對象數組到另一個數組,但是當我創建新的數組和其他函數我改變它的值,原來的數組也改變以及(這是不好)。我可以用另一種方式嗎? 這是一個例子:http://codepen.io/Xiwi/pen/rLMbYp分配對象內容數組到一個新的數組

回答

3

看起來你需要複製/克隆數組,以便它不會被引用改變。

如果只有Primitive Types數組,你可以這樣做的:

var test3 = JSON.parse(JSON.stringify(test2)); 

否則,你需要一個遞歸解決方案,並在你的問題更具體。

實施例:

var test1 = [{name: 'test1'}]; 
 
var test2 = [{name: 'test2'}]; 
 
var test3 = JSON.parse(JSON.stringify(test2)); 
 

 
test3[0].name = 'test3'; 
 

 
// Open console 
 
console.log('Test2: ',test2[0]); // Object {name: "test2"} 
 
console.log('Test3: ',test3[0]); // Object {name: "test3"}

+0

你沒有序列化,我相信'[] .splice(0,0,ARR);'會做原語 – kirinthos

+0

對不起'[] .concat(ARR)' – kirinthos

+0

@kirinthos副本沒有。就像那樣你會遇到同樣的問題。在這裏檢查:https://jsfiddle.net/jbL0vm9m/ – Sergio

0

對象基本上是引用。您必須創建一個新的對象,並指定另一個對象的值:

var test3 = [ Object.assign({}, test2[0]) ]; 
0

使用簡單.map複製對象到另一個的一個陣列。

var test1 = [{name: 'test1'}]; 
var test2 = [{name: 'test2'}]; 
//var test3 = test2.slice(0); //doesn't work. objects are still references 
var test3 = test2.map(function(obj){ 
    //return obj; //doesn't work. objects are still references 
    var o={}; //create brand new object 
    for(var prop in obj) 
    o[prop]=obj[prop];//assign properties 
    return o;//works 
}); 

test3[0].name = 'test3'; 

// Open console 
console.log('Test2: ',test2[0]); 
console.log('Test3: ',test3[0]); 
相關問題