Autumn Leonard Autumn Leonard - 3 months ago 9
Javascript Question

Why does this 2d array create unexpected results?

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

Answer

As Array is an object, you will see the actual (latest) value of that as console.log() shows a reference to the object and by the time you are opening it, the value has changed.

The option is to use console.dir() to print that current state of the object (although console.dir() does NOT work on chrome).

If you want to get the real value in chrome, print that one value, not whole object.
You can look at this post for expanded explanation and more info.

Comments