In the following code, I would expect a 2-dimensional array to be produced, pre-populated with zeros. The problem I am getting is that x[0][3] = 2
seems to be happening too quickly, so by the time of the console log inside the function, the array has a changed value already. I can't seem to remedy this, even with timeouts. What's going on?
function test(size) {
var row = [];
var return_me = [];
for (var i=0; i < size; i++) { row.push(0); }
for (var j=0; j < size; j++) { return_me.push(row.slice()); }
console.log("1:");
console.log(return_me);
return return_me;
}
var x = null;
console.log("0:");
console.log(x);
x = test(5);
console.log("2:");
console.log(x);
x[0][3] = 2;
console.log("3:");
console.log(x);
The unexpected result comes at the "1:" in the output, where I get:
0: 0
1: 0
2: 0
3: 2
4: 0