Megan Meluskey
Megan Meluskey

Reputation: 97

How do I compare a user input to items stored in an array?

This is my code. I am trying to make the hangman app. How do I compare my user input "userGuess" to the array "array" that split out from the randomly generated word "word".

I want to say if the "userGuess" is equal to any of the values in the array "array" print to the console: userGuess + "is correct".

$(document).ready(function () { console.log("ready!");

var randomWords = [
    "dog",
    "cat",
    "america",
    "bootcamp",
    "javascript",
    "philadelphia"
]
var word = randomWords[Math.floor(Math.random() * randomWords.length)]; {
    console.log(word);
}
var amount = word.length;
console.log(amount);

$("#display-word").on("click", function (event) {
    $("#word").html("New Word is: " + amount + " letters long.")
})

//event listener 
document.onkeyup = function (event) {
    var userGuess = event.key;
    console.log(userGuess);
    $("#guesses").append(userGuess + "-");

    var str = word;
    var array = str.split("");
    console.log(array);

    for (var i = 0; i < array.length; i++) {
        // console.log(array.length);
        if (userGuess === i) {
            console.log(userGuess + "is correct"); 

        }

    }














}//on key up

}); //doc.ready function

Upvotes: 2

Views: 272

Answers (5)

Akrion
Akrion

Reputation: 18525

You can simply use Array.includes. Consider this:

var randomWords = [ "dog", "cat", "america", "bootcamp", "javascript", "philadelphia" ]

var word = randomWords[Math.floor(Math.random() * randomWords.length)];

var userGuess = ['a', 'b', 'c'];
var wordArray = word.split("");

userGuess.map(x => 
  console.log(
  'word:', word, 
  ', guess:', x, 
  ', result:', wordArray.includes(x) ? 'Correct' : 'Wrong!')
)

This is a simplified example just to give you the idea but in your case just utilize includes and there is no need to do the for loop and compare each index etc.

Upvotes: 0

Max
Max

Reputation: 63

From what I can see the mistake in this is in your if statement where you trying to compare if the index (i) is equal to the event.key so it will never return true.

To access the actual item in the array you need to use this instead:

if (userGuess === array[i]) {
  console.log(userGuess + " is correct"); 
} else {
  console.log(userGuess + "is not correct")
}

You could as well improve this by using the includes() method directly on the string.

if (word.includes(userGuess)) {
  console.log(userGuess + " is correct");
} else {
  console.log(userGuess + " is not correct");
}

I hope it helps

Upvotes: 0

Pehota
Pehota

Reputation: 116

You can also use the Array.prototype.includes function although it's a relatively new one and it depends on which browser versions you're targeting. This will allow you to skip the for loop and make the code more readable and short.

const input = 'input';
const answers = ['this', 'that'];
if(answers.includes(input)) {
   // do stuff
}

Upvotes: 0

Andrew Bowman
Andrew Bowman

Reputation: 869

indexOf will return -1 if it is not in the list of answers, or the index of what it was in the answers

answers = ["orange", "apple", "pear"]
if (answers.indexOf(userGuess) != -1) {
    console.log(userGuess + "is correct"); 
}

Upvotes: 2

sadq3377
sadq3377

Reputation: 827

You're close in your for loop but you're comparing the userGuess to the index and not the actual value stored at that index.

Also, you can stop as soon as you find a match by using a break statement.

Try this:

for (var i = 0; i < array.length; i++) {
        // console.log(array.length);
        if (userGuess === array[i]) {
            console.log(userGuess + "is correct"); 
            break;
        }

    }

Upvotes: 0

Related Questions