Reputation: 1
I want to check in this guessing game if the color the user inputs is in the array list or not. but when u put a color that is in the list it keeps saying it isn't
var guess_input;
var target;
var colors = ["blue", "cyan", "gold", "gray", "green", "magenta", "orange",
"red", "white", "yellow"
]
var finished = false;
var guesses = 0;
var pos;
function do_game() {
var random_number = Math.floor(Math.random() * (colors.length - 1));
target = colors[random_number];
while (!finished) {
guess_input = prompt("I am thinking of one of these colors: \n\n" + colors.join() +
"\n\n What color am I thinking of?");
guesses++;
finished = check_guess();
}
}
function check_guess() {
if (colors.indexOf(guess_input) > -1) {
alert(
"This is not a color from the list ! Please pick a color from the list\n\n"
);
return false;
}
}
Upvotes: 0
Views: 155
Reputation: 1419
Your conditional is backwards:
function check_guess() {
if (colors.indexOf(guess_input) === -1) { // -1 means not found! you have > -1 which means found!
alert(
"This is not a color from the list ! Please pick a color from the list\n\n"
);
return false;
}
else return true;
}
You also need to return true in some case to avoid an infinite loop.
Upvotes: 3
Reputation: 24395
To check if the input is not in the list, you want == -1
, not > -1
.
if (colors.indexOf(guess_input) == -1) {
//the element was not found
Upvotes: 2