简体   繁体   中英

Array only being updated on first iteration of a for loop

The following code takes an array of objects structured like so: {html: whatever number: number value }.

function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}

Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?

You need to move the initialization of num outside of the for loop. Inside it creates for each iteration a new empty array.

BTW, no need for using another variable for data .

function Org(data){
    var nums = [];
    for (var i = 0; i < data.length; i++){
        nums.push(data[i].number);
    }
    console.log(nums);
}

或更短:

var Org=data=>console.log(data.map(e=>e.number));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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