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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With