3 回答

TA貢獻1853條經驗 獲得超18個贊
你有幾個問題。
首先,一旦發現不匹配,就從函數返回,但后面的元素winningPlays可能匹配。
其次,您期望xPlays完全匹配其中一個winningPlays元素。但是 X 可以有額外的玩法。例如,如果xPlays = [2, 3, 4, 5], that should match[3, 4, 5] . What you really want to test is if all the elements of one of thewinningPlays elements are included inxPlays`,它們不必具有相同的索引。
function checkForWinner() {
if (xPlays.length < 3) {
return;
}
for (let i = 0; i < winningPlays.length; i++) {
let win = true;
for (let j = 0; j < winningPlays[i].length; j++) {
if (!xPlays.includes(winningPlays[i][j])) {
win = false;
break;
}
}
if (win) {
console.log('win');
break;
}
}
}

TA貢獻1803條經驗 獲得超6個贊
遍歷每個子數組
檢查該子數組的所有項目是否都存在于玩家數組中
function checkWinner() {
return winningPlays.some(list => {
return list.every(item => {
return xPlays.includes(item);
});
});
}

TA貢獻1898條經驗 獲得超8個贊
我會通過執行以下操作使其更簡單
const winningPlays = [
"0,1,2", //across top
"3,4,5", //across middle
"6,7,8", //across bottom
"0,3,6", //left down
"1,4,7", //middle down
"2,5,8", //right down
"0,4,8", //top left to bottom right
"2,4,6" // top right to bottom left
]; //length == 8
function checkForWinner(xPlays) {
var convertXPlays = xPlays.toString(); //if there are spaces in your array, make sure to remove it
if (winningPlays.indexOf(convertXPlays) > -1)
{
console.log('win!');
}
};
添加回答
舉報