I am trying to change the value of a 2D array at index location [0][0], however the value at [1][0] gets changed as well. A different approach yields the correct value change at [0][0] without affecting any other value. Unable to understand the difference between the 2 methods.
Method 1:
function abc1(){
var dimArr=[2,3];
var arr=[];
var val=0;
for (var i=dimArr.length-1; i>=0; i--)
{
arr = [];
for(var k=0; k<dimArr[i]; k++)
arr.push(val);
val = arr;
}
return arr;
}
Method 2:
function abc2(){
var outterArray = [];
for(var i=0; i<2; i++)
{
var innerArray = [];
for(var j=0; j<3; j++)
{
innerArray.push(0);
}
outterArray.push(innerArray);
}
return outterArray;
}
When I run the script:
var d2= abc1();
d2[0][0]='a';
console.log(d2);
var d3= abc2();
d3[0][0]='a';
console.log(d3);
The variable d2 logs:
[["a", 0, 0], ["a", 0, 0]]
The variable d3 logs:
[["a", 0, 0], [0, 0, 0]]
Any ideas why?