What is the best way to check if a user input matches any of the items saved in an array?

I'm working on coding a hangman app and I have a question. How can I compare the user input "userGuess" to the array "array" that consists of letters split from the randomly selected word "word"?

If the "userGuess" matches any of the values in the "array", I want to log to the console: userGuess + "is correct".

$(document).ready(function() { console.log("I'm all set up and ready to go!");

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++) {
        if (userGuess === array[i]) {
            console.log(userGuess + " is correct");
        }
    }

}//end of keyup event

}); //end of document ready function

Answer №1

indexOf will provide a result of -1 if the answer is not included in the list, otherwise it returns the index position of the answer.

options = ["banana", "kiwi", "grapefruit"]
if (options.indexOf(userChoice) != -1) {
    console.log(userChoice + "is an available option"); 
}

Answer №2

When using a for loop, make sure to compare the userGuess to the value stored at each index rather than just comparing it to the index itself.

Additionally, you can optimize your code by stopping the loop as soon as you find a match using a break statement.

Consider trying this revised approach:

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

    }

Answer №3

An alternative approach is to leverage the Array.prototype.includes method, which is a relatively recent addition and may have varying support across different browser versions. By utilizing this method, you can eliminate the need for a traditional for loop, resulting in cleaner and more concise code.

const userInput = 'input';
const possibleAnswers = ['this', 'that'];
if (possibleAnswers.includes(userInput)) {
   // perform desired actions
}

Answer №4

It appears that the error lies within your if statement where you are attempting to compare the index (i) to the event.key, resulting in it never returning true.

To correctly access the item in the array, you should use the following instead:

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

An alternative way to enhance this would be to utilize the includes() method directly on the string.

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

I trust this clarifies the issue for you.

Answer №5

If you're looking to simplify your code, consider using Array.includes. For example:

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 just a simple illustration to demonstrate the concept. By utilizing includes, you can streamline your process without the need for cumbersome loops to compare each index.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my button to not capture the value of this input text field?

After clicking the button, I am trying to log the value of the input text field in the console. However, it just shows up as blank. Despite checking my code multiple times, I can't seem to figure out why. Any insights would be greatly appreciated! &l ...

Creating intricate JSON arrays through PHP code

I have extracted data from the database and created a JSON file with information from two tables. The first table, semone, contains attributes such as id, semester, and course name (cname) while the second table, courses, has attributes like course name (c ...

Is there a way I can retrieve my Nodemailer email and store it in a variable?

I am currently utilizing the nodemailer module in conjunction with node.js and have successfully implemented the following: let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<a href="/cdn-cgi/l/email ...

Is there a way to uncheck a checkbox by clicking on a link?

Just have a single checkbox for toggling: <label><input type="checkbox" name="myfield" id="myfield" />&nbsp;&nbsp;Enable Sound</label> Users can click on it to turn sound on the site. I'm looking for a way to uncheck the ch ...

Printing Elements of a Multidimensional Array in Java

I'm a little confused about why these numbers are being printed out. I thought it would just print 3, 2, 1. However, the output is: 3 0 0 0 2 0 0 0 1 Thank you so much for your assistance! :) public static void main(String[] args) { int ...

Leverage Reveal.js within Next.js by installing it as an npm package

I am currently working on a project that requires integrating Reveal.js with Next.js. However, I am having trouble displaying the slides properly. Every time I try to display them, nothing shows up. Even after attempting to display some slides, I still en ...

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

What is the best way to display a placeholder instead of the state's value when a page loads?

I'm having trouble displaying the placeholder of an input instead of its state value. When the page loads, it shows an empty select box because the testType state is null initially. How can I make sure that only the placeholder is shown instead of the ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

An exploration on integrating a controller into an Angular directive class using Typescript

Here's the TypeScript code for an Angular directive class I've been working on: I'm wondering how I can incorporate a controller into this directive without creating a separate controller class. My goal is to write and inject the ISOLATE SC ...

Guide to toggling the anchor tag functionality as a button with JavaScript

I am trying to dynamically enable or disable an anchor tag that is used as a button using JavaScript. Within a certain condition, I want to control the state of this button. Here is the specific button in question: <div class="row my-2 text-right& ...

Developing a custom JavaScript function to iterate through a group of html elements

In my mission to create a function that loops through a set of HTML elements and gathers their values, I aim to then utilize those values to produce an HTML textarea. Thus far, I've established a series of HTML input boxes and a JavaScript function f ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

Strategies for Resolving Table Alignment Problems using HTML and JavaScript

I am struggling to figure out how this dashboard will function as it is not a live website, but rather a tool that pulls data from a chemical analysis program and displays it in a browser view. My main issue is aligning two tables at the top of the page ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

Retrieve object containing all identical fields except for one specific field

Looking for help with filtering a JavaScript object [ { "comparing_result": "d_sens", "event": "Require", "master_field": "type_de_donnees", "master_field_ ...

JavaScript code to generate a UTF8 string from UTF codes

I am in possession of the byte representation of UTF8, such as: 195, 156 for "Ü" (capital U Umlaut) I am struggling to generate a JavaScript-compatible string from these numbers - all my attempts have been unsuccessful. Every method I have tried has mis ...

Transmitting array information between classes in JAVA

(I am new to this, so apologies if this is too basic or lacks details.) Currently, I am working with an ArrayList that stores attributes of various pets such as their given name, common name, price, gender, purchase date, and sale date. This data is popula ...