Struggling with properly locating a string within an array

I have been attempting to search an array for a specific string using a For loop, iterating through each index of the array based on its length. The expected behavior is that if the string is found, it should display that string (which in this scenario is a letter). However, even when the letter is present, the output does not get updated as intended.

For instance, take the word DOG. Initially, the output array would appear as '▢ ▢ ▢'. If I were to guess 'D', the output array should then update to 'D ▢ ▢'. Unfortunately, this update does not occur.

Below is the relevant code snippet:

function encryptLetters() {

    instructions.style.display = "none";
    
     for (i = 0; i < magicyMagic.length; i++) {
        
        if (magicyMagic.substring(i, i + 1) == " ") {
        
        output[i] = "&nbsp &nbsp";
            
    } else if (magicyMagic.substring(i, i + 1) == ".") {
        
        output[i] = ".";
            
    } else {
        
        output[i] = " ▢"
            
    }

  }


  document.getElementById("mysteryWord").innerHTML = output.join("");

  firstTurn();


}

function player1() {

  console.log("Player 1 is going.");
    nowGoing = 1;
    player1Elements.style.display = "block";
    
    alert(playerName1 + " it is your turn. What do you guess?");
  ask();

}

function ask() {

    console.log("Prompting");
    
    var guess = prompt("What letter would you like to guess?");
    var playerGuess = guess.toUpperCase();
    
    console.log(playerName1 + " guessed " + playerGuess);
    
    checkGuessType(playerGuess);

}

function checkGuessType(playerGuess) {

    console.log("Checking type...");

  if (playerGuess.length > 1) {

    console.log(playerName1 + " guessed a word.");

  } else if (playerGuess == ...

In the developer console, only the following messages are visible:

"The first player's name is Test1."
"The second player's name is Test2."
"The player(s) have been informed."
"The word is UGANDA"
"Player 1 is going."
"Prompting"
"Test1 guessed A"
"Checking type..."
"Test1 guessed a vowel."
"Checking if letter is present..."
"Ding ding ding!"
"Ding ding ding!"
"A has been added to the list. Players cannot guess this letter again."

Even though the console log statements related to updating the output array appear, the array itself remains unchanged. How can this issue be resolved?

P.S. Any variables not explicitly shown in the provided code snippet are most likely global variables, but their absence shouldn't impact the solution.

EDIT: Here is a list of all relevant variables - note that all array values are capitalized, yet the issue persists despite this fact.

var playerName1;
var playerName2;
var nowGoing = 0;
var magicyMagic;
var isCorrect = false;

// ____ Trees (types of trees - 1)
var array1Trees = ["OAK", "ELM", "PINE", "BIRCH", "SPRUCE", "ASPEN", "MAPLE", "CEDAR", "REDWOOD", "CHERRY"];
...

Answer №1

When dealing with string comparisons, it's important to remember that they are case sensitive. This means that lowercase and uppercase letters are considered different characters. For example, "e" is not the same as "E". In your current code, you're checking if the guessed letter is a vowel by comparing it only to "a", "e", "i", "o", and "u", but not their corresponding uppercase versions.

Due to this oversight, the message displayed reads "Test 1 guessed a consonant" even when the input was actually "E".

To address this issue, you can either include the uppercase letters in your comparison logic for case sensitivity or convert the player's guess to lowercase using the toLowerCase() function before performing the comparison.

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

The dynamic duo: Formik meets Material-UI

Trying to implement Formik with Material-UI text field in the following code: import TextField from '@material-ui/core/TextField'; import { Field, FieldProps, Form, Formik, FormikErrors, FormikProps } from 'formik'; import ...

Can you clarify the functionality of this loop? I am having trouble grasping how it produces the final result

Seeking clarification on the highlighted section] https://i.sstatic.net/dyrKS.png I need assistance in understanding how the use of "text" helps to print the following literal. ...

React setState issue experienced only on initial click due to API lag

My goal is to develop a web app using the Poke API to display multiple Pokemon. I have added buttons to allow users to "change the page" and switch the API URL to view the next or previous set of Pokemon. However, I'm facing an issue where the buttons ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

Discover the row and column of a selected table cell using vanilla JavaScript, no need for jQuery

In my JavaScript code, I am currently working on creating an onclick function that will display the row and column of a specifically clicked cell in a table. I have successfully implemented functionality to return the column number when the cell is click ...

PHP: Can someone guide me on generating a multidimensional array dynamically using specific retrieved values?

Consider this array: $array = array('key1', 'key2'); How can I transform the array above into something similar to this: $multiarray['key1']['key2'] = 'test'; This conversion should be possible regardle ...

What is the method to retrieve data in Vue when utilizing arrow functions?

When utilizing Vue and arrow functions in methods, we encounter the issue that arrow functions do not have a this keyword. The question then arises of how to access data properties such as list or object. export default { data() { return { list ...

JavaScript code to record the time when a client exits my website by clicking the X button in the top right corner and save it in my database

I need to record in the database the times when users enter and exit my site. Saving the entry time is not an issue, nor is saving the exit time by clicking my "log off" button. However, what about when a client exits by clicking the X in the right corner ...

Working with JSON data in Golang by parsing two arrays of arrays using a single struct

Imagine having access to the following data: { "code": 10000, "msg": "Request successfully processed", "asks": [ [ "0.03434400", "0.31100000" ], [ "0.03436300", "0.18900000" ], [ ], "bids": [ [ ...

How to stop parent event propagation in jQuery

I am facing a frustrating issue with my code. Every time I toggle a checkbox, the parent element's click event also triggers. I have experimented with various solutions like: event.stopImmediatePropagation(); event.stopPropagation(); event.preventD ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

Encountered an issue while trying to add images and text simultaneously in asp.net

I am trying to modify my code by adding an image along with the text. Here is the updated code: $(".ChatSend").click(function () { strChatText = $('.ChatText', $(this).parent()).val(); var recievertext= $('.ausern ...

Error with Chakra UI and React Hook Form mismatched data types

Struggling with creating a form using ChakraUI and React-Hook-Form in TypeScript. The errors seem to be related to TypeScript issues. I simply copied and pasted this code from the template provided on Chakra's website. Here is the snippet: import { ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Interconnected props in Material UI components interact with one another

Is there a way to have the value of one property in a Material UI component reference another property within the same component? For example, can I make the value property in a Switch component refer to the checked property? <Switch checked={sing ...

repairing a recursive backtracking program

Looking for an algorithm that utilizes recursive backtracking to generate all possible compositions of x1+x2+x3 that add up to a given number. For example, if the input number is 4, the method should output 3 results: 1 1 2 1 2 1 1 1 2 ...... Here's ...

Utilizing ng-class with Boolean values in AngularJS

On my page, I have a pair of buttons that control the visibility of elements using ng-hide and ng-show. <a ng-click="showimage=true" ng-class="{ 'activated': showimage}" class="button">Images</a> <a ng-click="showimage=false" ng-c ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

Converting a string to an array: A comprehensive guide

Converting a string variable into an array: $checkedValues = $_POST['checkedValues']; The initial value of the variable $checkedValues is '257, 259, 261' Array ( [0] => 257, 259, 261 ) How can we transform this variable into an ...