简体   繁体   English

仅在for循环的第一次迭代时更新数组

[英]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 }. 以下代码采用如下结构的对象数组:{html: 无论数字: 数字值 }。

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. 当调用时,Nums应该在第二次迭代时以[1,1]的形式记录到控制台:[{html:null,number:1},{html:null,number:1}]但是记录为[1] ]在第一次和第二次迭代中。 Why might this be? 为什么会这样?

You need to move the initialization of num outside of the for loop. 您需要在for循环之外移动num的初始化。 Inside it creates for each iteration a new empty array. 在里面它为每次迭代创建一个新的空数组。

BTW, no need for using another variable for data . 顺便说一句,不需要为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));

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

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