Autumn Leonard Autumn Leonard - 1 year ago 81
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()); }
return return_me;

var x = null;
x = test(5);
x[0][3] = 2;

The unexpected result comes at the "1:" in the output, where I get:

0: 0
1: 0
2: 0
3: 2
4: 0

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download