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
temparray in the inner loop so you’re not reusing the same array over and over:Since assigning the
temparray into thepopulationarray only puts a reference to thetemparray in, when you keep using the sametemparray over and over again, you end up with references to the sametemparray at each index of thepopulationarray. If, instead, you create a newtemparray in the inner loop, then each array in thepopulationarray will be different.FYI, I also made some other corrections to your code to properly declare the variables
temp,iandjas local variables so they aren’t implicit global variables.