简体   繁体   中英

Array not storing values in for loop

Im parsing a json object and storing the values I want in an array, I then push each array into a second array inside the for loop to create an array where each element in a2 is a1 .

Im already getting and parsing the json correctly.

var a1 = [];
var a2 = [];

for(i = 0; i < json.results.query.length; i++) {
   var date = json.results.query[i].Date;
   var name = json.results.query[i].Name;

   a1[0] = date;
   a1[1] = name;

   console.log(a1);
   a2.push(a1);
}

console.log(a2);

console.log(a1) prints the correct array, which changes for each iteration of the for loop. For example:

["2014-01-01", "John"]
["2014-01-02", "Ann"]
["2014-01-03", "Mike"]

But console.log(a2) prints the a2 array with the last a1 values for every index:

[["2014-01-03", "Mike"],
["2014-01-03", "Mike"],
["2014-01-03", "Mike"]]

I also tried assigning a1 to each index of a2 inside the for loop instead of using .push() such as:

a2[i] = a1;

I want the nested (or 2-d) array, but why is each element the same?

What is going on here? Is there some javascript scoping rule? This works in other languages. Thanks!

I think you need a2.push(a1); not a2.push(a2); (in for-loop)

Or try this:

for(i = 0; i < json.results.query.length; i++) {
   var date = json.results.query[i].Date;
   var name = json.results.query[i].Name;

   a2.push([date, name]);
}

Note: In first way, you should declare a1 inside the for-loop NOT outside at top of it.

Each time you go around the loop you modify the existing array referenced by a1 and then push a reference to it into the array referenced by a2 .

This means you end up with multiple references to the same array.

You need to create a new array to push for each set of data.

Move var a1 = []; inside the loop.

a1 is a reference of your array object, and your for loop is keeping changing the object value.

you need to copy a1 value to some variable first then push the variable to a2.

try:

var a1 = [];
var a2 = [];
function pushToA2(a){
 a2.push(a);
} 

for(i = 0; i < json.results.query.length; i++) {
  var date = json.results.query[i].Date;
  var name = json.results.query[i].Name;

  a1[0] = date;
  a1[1] = name;

  pushToA2(a1);

}

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