为什么这个二维数组会产生意想不到的结果?

Why does this 2d array create unexpected results?

在下面的代码中,我希望生成一个二维数组,并预先填充零。我遇到的问题是 x[0][3] = 2 似乎发生得太快了,所以当函数内的控制台日志出现时,数组的值已经改变了。我似乎无法解决这个问题,即使有超时。怎么回事?

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);

意外结果出现在输出中的“1:”处,我得到:

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

由于 Array 是一个对象,您将看到它的实际(最新)值,因为 console.log() 显示了对对象的引用 并且当您打开它,值已经改变了。

选项是使用 console.dir() 打印对象的当前状态(尽管 console.dir() 不适用于 chrome)。

如果你想获得 chrome 中的真实值,打印那个值,而不是整个对象。
您可以查看 this post 以获取详细说明和更多信息。