为什么我的对象只保存最后的数据

Why my object save only last data

我正在创建两个对象,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();

您在推送时使用相同的对象引用。

你可以在赋值和推送之前获取一个新对象,比如

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
}

一个更好的方法是使用一个函数来构建结构并为注释取一个参数:

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
}