简体   繁体   English

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

[英]Why my object save only last data

I'm creating two objects, struct_one and the auxiliary struct_two for primary save a data. 我创建两个对象, struct_one和辅助struct_two小学保存数据。 After adding data with the help of .push . .push的帮助下添加数据之后。 Everything data from the struct_one array, have a last the data. 来自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(); 

You use the same object reference on pushing. 您在推送时使用相同的对象引用。

You could take a new object before assigning values and pushing, like 您可以在分配值和推送之前先获取一个新对象,例如

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
}

A slighy better way, is to use a function for building the structure and take a parameter for the comment: 一种更好的方法是使用一个函数来构建结构并为注释添加一个参数:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM