在下面的代碼中,我期望生成一個二維數組,並預先填充零。我得到的問題是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
您發現意外的日誌結果是什麼? –
對不起,這是誤導性的:沒有錯誤。我用更具體的問題更新了這個問題,以便更清楚。 –