简体   繁体   中英

Nested For loop for initializing array of arrays for Javascript

I have a very simple part of my program here that's having a problem... The elements in the array 'population' are also an array.. having 28 random numbers each 'temp' array that is being loaded to the array population. My problem is that the array 'population''s somehow have all the same arrays saved in it, it's like its being override every loop. Ive spent so much time in this very simple problem, is this some kind of bug?? The commented 'alert' is used to check the element 0 and 1 of the population. and somehow it's really being overriden every loop so every temp elements in the population array is all the same. Please help me..

var population[];
function init_population(){   
    temp = [];
    //Math.floor(Math.random()*8);
    for(i=0;i<10;i++){
        for(j=0;j<28;j++)
        temp[j] = Math.floor(Math.random()*8);
        population[i]= temp;
    //alert("population[0] = " +population[0] +" and population[1] = " +population[1]);
    }
}

init_population();

You need to create a new temp array in the inner loop so you're not reusing the same array over and over:

var population = [];

function init_population() {   
    var temp, i, j;
    for(i=0; i<10; i++) {
        temp = [];
        for(j=0; j<28; j++) {
            temp[j] = Math.floor(Math.random()*8);
        }
        population[i] = temp;
    }
}

init_population();

Since assigning the temp array into the population array only puts a reference to the temp array in, when you keep using the same temp array over and over again, you end up with references to the same temp array at each index of the population array. If, instead, you create a new temp array in the inner loop, then each array in the population array will be different.


FYI, I also made some other corrections to your code to properly declare the variables temp , i and j as local variables so they aren't implicit global variables.

This is because it's the same array. You create it with temp = [] and then assign it to each of the population[i] for i=0..9

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