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.
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.
Share Improve this question asked Nov 7, 2015 at 14:22 Emil MladenovEmil Mladenov 3201 gold badge4 silver badges10 bronze badges 1-
2
options.indexOf(choice) >=0
– Jaromanda X Commented Nov 7, 2015 at 14:23
2 Answers
Reset to default 9Instead 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');
}
You can check if the array contain an item without a loop Using indexOf method searches the array for the specified item, and returns its position, and returns -1 if the item is not found, e.g :
var options = ['rock','paper','scissors'];
var choice = 'scissors';
//If the input does not match any of the array objects prompt the user for a new input
if (options.indexOf(choice) == -1)
{
prompt("Enter new input");
}
Hope this helps.