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;
}
数据格式如下
{"name":"RYI","id":2,"name":"BIB","id":1}
我想访问上述数据,将每个名称和ID存储在名为
lob
的对象中,并将每个对象存储在数组returnLOB
中。每次循环通过
console.log(lob)
时,都会得到正确的对象,例如:RYI id:2和BIB id:1,然后但是,当我尝试将它们存储在
returnLOB
数组中时,它将第二个对象输出两次,而不是每个对象一次。知道这里有什么问题吗?
最佳答案
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;
}
将lob的声明移入循环。现在,您正在重用同一对象,并将其多次添加到数组中。每次通过循环,都会更新同一对象。