I am getting two different results for doing which I believe is the same thing in javascript with array push. Since I am new to javascript, I might be missing the big picture here.
Sample 1 -
class Test {
constructor(){
this.matrix = [];
}
createMatrix(){
this.matrix.push([0,0,0]);
this.matrix.push([0,0,0]);
this.matrix.push([0,0,0]);
}
addNodes(x, y){
this.matrix[x][y] = 1;
this.matrix[y][x] = 1;
}
printMatrix(){
return this.matrix;
}
}
let test = new Test();
test.createMatrix();
console.log(test.printMatrix());
test.addNodes('1','2');
console.log(test.printMatrix());
O/p -
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]
Sample 2 -
Replacing the createMatrix method with below one, gives me another result when trying to addNodes.
createMatrix(){
let row = [0,0,0];
this.matrix.push(row);
this.matrix.push(row);
this.matrix.push(row);
}
O/p -
[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 0, 1, 1 ], [ 0, 1, 1 ], [ 0, 1, 1 ] ]
Please help me understand what I am missing out here, I want to achieve is o/p of sample 1 with the sample 2 code.