當作為索引號的陣列在另一個陣列的索引上具有指定符號時,checkWin 函式回傳 true。如何從嵌套的 winConditions 陣列中檢索結果為 true 的“cond”(陣列)?
使用單擊事件偵聽器填充符號。
預期的結果應該是,如果 .some(cond) 變為真,則回傳該條件,例如。如果 [0, 1, 2] 上存在符號“X”,則回傳此陣列
let testArray = Array(9).fill("")
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],
];
let xValue = "X";
let oValue = "O";
function checkWin(value, array) {
return winConditions.some((cond) =>
cond.every((index) => array[index] == value));
}
console.log(checkWin(xValue, testArray));
console.log(checkWin(oValue, testArray));
uj5u.com熱心網友回復:
您可以使用.find()代替.some(),這將回傳.every()回呼回傳的第一個陣列true。您可以使用此陣列來確定特定玩家是否獲勝:
const testArray = Array(9).fill("");
testArray[3] = testArray[4] = testArray[5] = "O"; // test winning position
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 xValue = "X";
const oValue = "O";
function getWinPos(value, array) {
return winConditions.find((cond) =>
cond.every((index) => array[index] == value)
);
}
const xWinPos = getWinPos(xValue, testArray);
const oWinPos = getWinPos(oValue, testArray);
if(xWinPos) { // found a winning position row/col/diag for "X"
console.log(xWinPos);
} else if(oWinPos) { // found a winning row/col/diag for "O"
console.log(oWinPos);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451016.html
標籤:javascript 数组 多维数组
上一篇:帶有OpenMP的C 盡量避免緊密回圈陣列的錯誤共享
下一篇:從切片中洗掉字串切片
