3 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
你有幾個(gè)問題。
首先,一旦發(fā)現(xiàn)不匹配,就從函數(shù)返回,但后面的元素winningPlays可能匹配。
其次,您期望xPlays完全匹配其中一個(gè)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貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
遍歷每個(gè)子數(shù)組
檢查該子數(shù)組的所有項(xiàng)目是否都存在于玩家數(shù)組中
function checkWinner() {
return winningPlays.some(list => {
return list.every(item => {
return xPlays.includes(item);
});
});
}

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
我會(huì)通過執(zhí)行以下操作使其更簡單
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!');
}
};
添加回答
舉報(bào)