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!');
}
};
添加回答
举报