這個問題在這里已經有了答案: 為什么相同的值會被寫入陣列 5 次? (2 個回答) 2 小時前關閉。
我正在撰寫國際象棋代碼并嘗試將偽合法移動推入陣列中,在推入之前我正在記錄它并且它是正確的,并且在推入之后它也是正確的,但是當我記錄陣列時它推錯了東西。
if (this.colour == 'white') {
this.moveOffsets.yOffset = -1 * tileSize;
}
else {
this.moveOffsets.yOffset = 1 * tileSize;
}
pseudoLegalPos.length = 0;
pseudoLegalPos.push(this.x, this.y this.moveOffsets.yOffset);
console.log(pseudoLegalPos);
this.pseudoLegal.push(pseudoLegalPos);
console.log(pseudoLegalPos);
}
此外,當我記錄陣列時,它最終推送了一個應該稍后在函式中推送的值。
uj5u.com熱心網友回復:
假設這是一個回圈,做
pseudoLegalPos.length = 0;
pseudoLegalPos.push(...);
this.pseudoLegal.push(pseudoLegalPos);
只會將同一pseudoLegalPos陣列的多個副本推送到this.pseudoLegal.
你想要的機會
const pos = [this.x, this.y this.moveOffsets.yOffset];
this.pseudoLegal.push(pos);
取而代之的是全新的poses。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/505119.html
標籤:javascript 数组
上一篇:JS選擇沒有ID的長度
下一篇:如何在for回圈中對數字求和?
