2017-10-01 86 views
2

我創建兩個對象struct_one和輔助struct_two用於主保存數據。 在.push的幫助下添加數據後。來自struct_one數組的所有數據都有最後一個數據。爲什麼我的對象只保存最後的數據

var struct_one = { comments:[{comment:String}] }; 
 
var struct_two = {comment:String}; 
 

 
function taskElementWork() { 
 

 
    this. createBlockSaveNew = function() { 
 
    struct_two.comment = 1 + "RED"; 
 
    struct_one.comments.push(struct_two); 
 
    console.log(struct_one.comments[1].comment); // = 1RED 
 
    struct_two.comment = 2 + "RED"; 
 
    struct_one.comments.push(struct_two); 
 
    console.log(struct_one.comments[2].comment); // = 2RED 
 
    struct_two.comment = 3 + "RED"; 
 
    struct_one.comments.push(struct_two); 
 
    console.log(struct_one.comments[3].comment); // = 3RED 
 

 
    console.log(struct_one.comments[1].comment); // = 3RED -> Why! 
 
    } 
 
} 
 

 
test = new taskElementWork(); 
 
test.createBlockSaveNew();

+0

你能整理你的縮進嗎? – dwjohnston

+0

它可能是一個索引問題?也許從struct_one.comments [0] .comment開始,然後轉到1,然後轉到2 –

+0

另外'this.createBlockSaveNew'中的'this'可能不符合您的想法。 – Andy

回答

3

你用力推同一對象的引用。

你可以分配值和推搡,像

function taskElementWork() { 
    var struct_two = { comment: '' }; 
    struct_two.comment = 1 + "RED"; 
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[1].comment); // = 1RED 

    struct_two = { comment: '' }; 
    struct_two.comment = 2 + "RED"; 
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[2].comment); // = 2RED 

    var struct_two = { comment: '' }; 
    struct_two.comment = 3 + "RED"; 
    struct_one.comments.push(struct_two); 
    console.log(struct_one.comments[3].comment); // = 3RED 
} 

一個slighy更好的辦法之前,採取一個新的對象,是使用功能,建築結構,並採取一個參數評論:

function taskElementWork() { 
    function buildStructure(comment) { 
     return { comment: comment }; 
    } 

    struct_one.comments.push(buildStructure(1 + "RED")); 
    console.log(struct_one.comments[1].comment); // = 1RED 

    struct_one.comments.push(buildStructure(2 + "RED")); 
    console.log(struct_one.comments[2].comment); // = 2RED 

    struct_one.comments.push(buildStructure(2 + "RED")); 
    console.log(struct_one.comments[3].comment); // = 3RED 
} 
+0

謝謝。我明白了。 – Tflag

相關問題