【问题标题】:Why my object save only last data为什么我的对象只保存最后的数据
【发布时间】:2017-10-01 08:55:07
【问题描述】:

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

【问题讨论】:

  • 你能整理一下你的缩进吗?
  • 会不会是索引问题?也许从 struct_one.cmets[0].comment 开始,然后转到 1,然后是 2
  • 另外this in this.createBlockSaveNew 可能不会像你认为的那样做。
  • 如果以 struct_one.cmets[0].comment 开头,结果将是 "String() { [native code] }"

标签: javascript object push


【解决方案1】:

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

您可以在分配值和推送之前获取一个新对象,例如

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
}

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2010-09-29
    • 2012-06-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多