在下面的代码中,我期望生成一个二维数组,并预先填充零。我得到的问题是x[0][3] = 2
似乎太快了,所以在控制台登录函数的时候,数组已经有了一个改变的值。我似乎无法弥补这一点,即使超时。这是怎么回事?这个2d数组为什么会产生意想不到的结果?
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
是否有一个实际的_error_参与或日志只是看起来意外? – Xufox
您发现意外的日志结果是什么? –
对不起,这是误导性的:没有错误。我用更具体的问题更新了这个问题,以便更清楚。 –