Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking for a variable match with an array in JavaScript

I am teaching myself JavaScript and I want to write a simple program that will check if a user input is in a pre-existing array.

example code is:

 var options = ['rock','paper','scissors'];
 var choice = 'scissors';



var i;

    for (i=0;i<options.length;i++){
        if (choice === options[i]){
            console.log('match');
        }

    }

I tried with adding an else, that would prompt the user to enter a new input, but it runs every time the for loops goes through the array objects that don't match the input.

My end goal is to have this little program prompt the user for a new input only once when it detects that their input does not match any of the array objects.

like image 982
Emil Mladenov Avatar asked Sep 14 '25 14:09

Emil Mladenov


1 Answers

Instead of using a for loop you can use an if statement.

var options = ['rock', 'paper', 'scissors'];
var choice = 'scissors';

if(options.indexOf(choice) !== -1) {
  console.log('match');
}

The Array.indexOf() method searches the array for a value and returns -1 if it doesn't exist in the array.

So you can do the opposite and see if there isn't a match.

if(options.indexOf(choice) === -1) {
  console.log('no match');
}
like image 197
Lupin Ken Avatar answered Sep 17 '25 05:09

Lupin Ken