3 回答

TA貢獻1845條經驗 獲得超8個贊
首先數組不能比較
試試這個例子
let a = [0,2,3]
let b = [0,2,3]
alert( a === b )
您需要了解的是,當您保存數組時。您實際上所做的是在內存中創建對該數組的引用。
然后再次嘗試這個例子
let a = [0,2,3]
let b = a
alert( a === b )
你會明白的,為什么?因為在第一種情況下,您嘗試在內存中使用兩個單獨的地址。這意味著a & b 地址不同但相同kind of apartment。但在第二種情況下,您正在比較相同的地址。
因此,最簡單的方法是將它們轉換為字符串,然后嘗試比較它們。
JSON.stringify(a)==JSON.stringify(b)
然后你就會得到你想要的結果。雖然如果這些數組實例的屬性順序始終相同,那么這可能會起作用,但這為極其討厭的錯誤敞開了大門,這些錯誤可能很難追蹤。

TA貢獻1827條經驗 獲得超8個贊
如果不是忘記返回值并將 if 移到外部,那么您的最后一個示例是正確的。
const winConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
const squaresIndices = [0, 4, 8];
const isWin = winConditions.some(
(arr) =>
{
// return if this combination is matching or not
return arr.every(
(square) =>
{
// return if the value matches or not
return squaresIndices.includes(square);
}
);
}
);
// Then test the result
if (isWin)
{
alert("Game Over");
}

TA貢獻1805條經驗 獲得超10個贊
winConditions.forEach((array) => {
if(JSON.stringify(array)==JSON.stringify(squaresIndices)){
alert("Game Over")
}
})
您不能直接在 JavaScript 中比較兩個數組。您需要將其轉換為字符串以進行比較。您還可以使用 toString() 而不是 JSON.stringify()
添加回答
舉報