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

时间:2017-10-01 08:55:08

标签: javascript object push

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




1 个答案:

答案 0 :(得分: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
}

更好的方法是使用函数构建结构并为注释提供参数:

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
}