Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a variable type number with an array using indexOf in Javascript

Tags:

I have added a click event listener to a button. It calls the buttons YES AND NO. Basically the indexOf checks if the value in the variable foto is in the yesMeetup array or in the notMeetup array.

I tried to debug but I always get "You got it" and it's not calling the debugger when I click on NO button

let foto = Math.floor(Math.random() * 20) + 1;

document.querySelector('.btn').addEventListener('click', verify);

function verify() {
   var yesMeetup = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15];
   var notMeetup = [16, 17, 18, 19, 20];
   var notButton = document.getElementById('no');
   var yesButton = document.getElementById('yes');
   var decisao = document.getElementById('decisao');
   debugger;

   if (yesButton) {

        if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "You got it";
      } else if (notMeetup.indexOf(foto)) {
         decisao.textContent = "wrong";
      }

   } else if (notButton) {

      if (notMeetup.indexOf(foto)) {
         decisao.textContent = "You Gou it";
      } else if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "Wrong";
      }

   }
}
like image 706
Bruno Silva Avatar asked Feb 23 '19 19:02

Bruno Silva


People also ask

Does indexOf work on arrays?

IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.

How do you check if an array has a specific value in JavaScript?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

What is the function of the indexOf () in arrays?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

An if statement will evaluate anything passed into it as a boolean.

The only values for which it will not execute the "true" branch are all falsy values: 0, null, undefined, '', false, NaN.

Array.prototype.indexOf returns -1 when an element is not present in an array, which is not one of the falsy values and thus your if condition

if (array.indexOf(element))

will always evaluate as true.

var example = [1,2,3];
if (example.indexOf(4)) {
  console.log('still true');
}

You can use a direct comparison to -1:

var example = [1,2,3];
if (example.indexOf(4) !== -1) {
  console.log('this is not logged');
}

Or a newer, a bit cleaner, Array.prototype.includes:

var example = [1,2,3];
if (example.includes(4)) {
  console.log('this is not logged');
}
like image 164
nem035 Avatar answered Sep 20 '22 03:09

nem035