Javascript 2D Array Generation Doesn't Work As Intended
I am new here, and to programming as well. Anyway, to get in topic I wrote the following program with the purpose of generating a 2 dimensional array in JavaScript, and then displa
Solution 1:
You are adding the same array to array1
, again and again. Instead you need to create new arrays every time.
var array1 = [];
for (var i = 0; i < 10; i++ ) {
var array2 = [];
for (var j = 0; j < 10; j++) {
array2[j] = (i+1) + "-" + (j+1);
}
array1[i]=array2;
}
But normally, this will be done with Array.prototype.push
method, like this
var array1 = [];
for (var i = 0; i < 10; i++ ) {
var array2 = [];
for (var j = 0; j < 10; j++) {
array2.push((i+1) + "-" + (j+1));
}
array1.push(array2);
}
Solution 2:
You can create new array each time after assigned array2
to array1
, something like this
array2=[];
on
for (var i = 0; i < 10; i++ ) {
for (var j = 0; j < 10; j++) {
array2[j] = (i+1) + "-" + (j+1);
}
array1[i]=array2;
array2=[]; //created new array each time after array2 assigned
}
Post a Comment for "Javascript 2D Array Generation Doesn't Work As Intended"