javascript - 使用 Javascript .includes 指定多个整数

标签 javascript arrays

仅当单个条件中的所有整数与列表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/

相关文章:

javascript - 如何在jssor slider 中放置下拉菜单

javascript - 内联 JavaScript : can it retrieve reference to the element it was invoked from?

c++ - 我不明白 sizeof() 和数组给出的值

php - 数组索引与 array_fill php 一起消失

php - HTML:单选按钮数组

java - 第一次使用数组,尝试创建频率表

c++ - 为什么 offsetof(member) 等于 sizeof(struct)?

javascript - 根据值 : Javascript 从对象数组中选择一个属性

javascript - 语义用户界面下拉列表中的简单不可点击文本

javascript - 在 Angular 智能表中选择 st-search 不适用于 ng-model