user15394810
user15394810

Reputation: 1

why does this .include() not return true when all args are true?

I'm never getting the GAME OVER log even when all 3 are in the array.

const lostCheck = function () {
  if (arr.includes(diceNum1, diceNum2, bothDice)) {
    console.log("GAME OVER");
  } else {
    console.log("still playing...");
  }
};

I'm very new to this so please bear with me.

Thanks

Upvotes: 0

Views: 75

Answers (3)

Riyaz Khan
Riyaz Khan

Reputation: 3258

The Javascript's includes methods take only max two arguments.

  1. Param 1: Value to find
  2. Param 2: From index (Start finding value from which index)

In your case, you are passing 3 arguments, and you are trying to check if any of three is in the array, and this way, it doesn't work.

If you are looking to check if any of the dice is inside, this might help you:

let arr = [2, 4, 5, 3, 10]
const lostCheck = function () {

  let gameOverDices = [6, 4, 3]

  if (isGameOver(arr, gameOverDices)) {
    console.log("GAME OVER");
  } else {
    console.log("still playing...");
  }

};

function isGameOver (arr, gameOverDices) {
  return arr.some(item => gameOverDices.includes(item))
}

lostCheck()

Upvotes: 0

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

As pointed by Péter Leéh, includes only check against one argument. You can use every to loop over array and check if every entry is included in second array, like this:

let everyDiceIncluded = [diceNum1, diceNum2, diceNum3].every((dice) =>
  arr.includes(dice)
);
if (everyDiceIncluded) {
  console.log("GAME OVER");
} else {
  console.log("still playing...");
}

Upvotes: 2

Péter Leéh
Péter Leéh

Reputation: 2119

includes only accepts one value to search for (and the rest of the arguments are interpreted as fromIndex, see docs). If you need search for multiple values, then use the appropriate conditions:

const lostCheck = function () {
  if (arr.includes(diceNum1) && arr.includes(diceNum2) && arr.includes(bothDice)) {
    console.log("GAME OVER");
  } else {
    console.log("still playing...");
  }
};

Upvotes: 2

Related Questions