仅当单个条件中的所有整数与列表playerNumbers 中的整数相同时,我才尝试发出警报。第一组 (1 && 2 && 3) 有效,但任何高于此值的 (4 && 5 && 6) 都无效,因为 4 及之后的值包括 1 、 2 和 3 ,从而使第一个条件成立。我该怎么做才能使其仅在指定特定值时才满足条件?
function determinePlayerWin() {
if (playerNumbers.includes(1 && 2 && 3)) {
alert('player win!');
}
else if (playerNumbers.includes(4 && 5 && 6)) {
alert('player win!');
}
else if (playerNumbers.includes(7 && 8 && 9)) {
alert('player win!');
}
else if (playerNumbers.includes(1 && 4 && 7)) {
alert('player win!');
}
else if (playerNumbers.includes(2 && 5 && 8)) {
alert('player win!');
}
else if (playerNumbers.includes(3 && 6 && 9)) {
alert('player win!');
}
else if (playerNumbers.includes(1 && 5 && 9)) {
alert('player win!');
}
else if (playerNumbers.includes(3 && 5 && 7)) {
alert('player win!');
}
}
最佳答案
作为单个表达式的 &&
链,其中每个条件均为真,将计算出最后一个值,例如
.includes(1 && 2 && 3)
与
相同.includes(3)
相反,请使用数组并检查数组的每个
元素是否包含在playerNumbers
中:
if ([1, 2, 3].every(num => playerNumbers.includes(num))) {
// win
}
您还可以为每个 win 数组创建一个数组,以使代码更加干燥,例如:
const winArrs = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
// ...
];
if (winArrs.some(winArr => (
winArr.every(num => playerNumbers.includes(num)))
)) {
// win
}
关于javascript - 使用 Javascript .includes 指定多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837999/