简体   繁体   English

Javascript将对象存储在数组中

[英]Javascript storing objects in an array

function(data) {
    var lob = new LOBslist(); //new object
    var returnLOB = []; //array init
    for (var i1r= 0; i1r < data.length; i1r++) { 
        var cLob = data[i1r];
        lob.name = cLob.name;
        lob.id = cLob.id;

        returnLOB.push(lob); //adding to array?
        console.log(lob); //right here
  }

  console.log(returnLOB);
  return returnLOB;
}

data is in a format like 数据的格式如下

{"name":"RYI","id":2,"name":"BIB","id":1}

I want to access the above data, store each name and id in an object called lob and store each object in an array returnLOB . 我想访问上面的数据,将每个名称和id存储在一个名为lob对象中,并将每个对象存储在一个数组returnLOB

Every time I loop through and console.log(lob) , I get correct objects like: RYI id:2 and BIB id:1 then 每次我循环通过和console.log(lob) ,我得到正确的对象,如: RYI id:2BIB id:1 then

but when I try to store them in the returnLOB array it outputs the second object twice rather than each object once. 但是当我尝试将它们存储在returnLOB数组中时,它会输出第二个对象而不是每个对象一次。

Any idea what is wrong here? 知道这里有什么问题吗?

function(data) {
        var returnLOB = []; //array init
        for (var i1r= 0; i1r < data.length; i1r++) { 
                var lob = new LOBslist(); //new object
                var cLob = data[i1r];
                lob.name = cLob.name;
                lob.id = cLob.id;

                returnLOB.push(lob); //adding to array?
                console.log(lob); //right here

        }

        console.log(returnLOB);
        return returnLOB;

    }

Move the declaration of lob into the loop. 将lob的声明移动到循环中。 Right now you are reusing the same object and adding it to the array multiple times. 现在,您正在重复使用相同的对象并将其多次添加到数组中。 Each time through the loop the same object is updated. 每次通过循环时,都会更新相同的对象。

Try creating the lob object each time, otherwise you're just adding the same one over and over and changing it's values each time. 尝试每次都创建lob对象,否则你只是反复添加相同的对象并每次更改它的值。 Plus, your code could be simplified by using a "for...in" loop, as shown: 另外,通过使用“for ... in”循环可以简化代码,如下所示:

function(data) {
    var lob;
    var returnLOB = []; //array init
    for (var cLob in data) { 
            lob = new LOBslist(); //new object
            lob.name = cLob.name;
            lob.id = cLob.id;

            returnLOB.push(lob); //adding to array?
            console.log(lob); //right here
    }

    console.log(returnLOB);
    return returnLOB;
}

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

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