2017-10-01 3 views
2

私はプライマリのデータを保存するために、struct_oneと補助struct_twoの2つのオブジェクトを作成しています。 .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() { 
    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 
} 

あなたがより良い方法を値を割り当てると

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のように、プッシュする前に新しいオブジェクトを取ることができ、構造を構築するための機能を使用し、コメントのパラメータを取ることです

+0

ありがとうございます。私は理解されています。 – Tflag

関連する問題