Unexpected result produced by indexOf() function

When trying to display the index of the first element (violet) using an alert, I am getting -1 instead of the expected result. This unexpected outcome is hindering my progress in coding. As a newcomer to JavaScript, I'm facing this issue and seeking assistance to move forward. I hope someone can provide a solution promptly.

var colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"];
var target;
var target_index;
var guess_input;
var finished = false;

function do_game() {
var random_number = Math.random() * 7;
var random_number_integer = Math.floor(random_number);
var target_index = random_number_integer;
target = colors[target_index];
alert(target);
while (!finished) {

var guess_input = prompt("I am thinking of a color " +
"violet,indigo,blue,green,yellow,orange,red" +
"What is the color?");
alert(colors.indexOf(guess_input));
finished = check_guess();
}
}

function check_guess() {

if (colors.indexof(guess_input) < 0) {
alert('not present');
return false;
}
if (guess_input > target) {
alert('you gave large');
return false;
}
if (guess_input < target) {
alert('you gave small');
return false;
}
return true;
}

Answer №1

You mentioned that your user_input is purple and the result is -1

It is expected behavior as purple is not included in the array provided

["voilet","indigo","blue","green","yellow","orange","red"];

There seems to be a typo: you entered voilet instead of purple

Answer №2

Make sure to double-check the spelling of "violet" within your array.

Also, ensure that your code includes the following:

if (colors.indexOf(guess_input) < 0) {
    alert('not present');
    return false;
  }

There is a small error here that needs correcting:

colors.indexOf(guess_input)

Answer №3

guess_input is declared within the do_game function using the var keyword, making it local to that function and not accessible globally.

To make guess_input accessible in other methods, you would either need to remove the var declaration or pass it as a parameter to the other methods.

/* corrected spelling error */
var colors = ["violet", "indigo", "blue", "green", "yellow", "orange", "red"];
var target;
var target_index;
var guess_input;
var finished = false;

function do_game() {
  var random_number = Math.random() * 7;
  var random_number_integer = Math.floor(random_number);
  var target_index = random_number_integer;
  target = colors[target_index];
  alert(target);
  while (!finished) {
    /* removed var keyword here */
    guess_input = prompt("I am thinking of a color " +
      "violet,indigo,blue,green,yellow,orange,red" +
      "What is the color?");
    alert(colors.indexOf(guess_input));
    finished = check_guess();
  }
}

function check_guess() {

  /* fixed a typo here */
  if (colors.indexOf(guess_input) < 0) {
    alert('not present');
    return false;
  }
  if (guess_input > target) {
    alert('you guessed too large');
    return false;
  }
  if (guess_input < target) {
    alert('you guessed too small');
    return false;
  }
  return true;
}

do_game()

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

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

How to target the last child in Flexbox using CSS order property

Is there a way to correctly detect the last child after rearranging divs using flex order? Even though I have set the order in the CSS, it is still recognizing the last child based on the DOM tree. Since the items are dynamic, we can't rely on nth-chi ...

How can I find the week of the month using Moment.js? (similar to Google Calendar)

Currently leveraging the fantastic features of Moment.js, I am facing a dilemma. How can I determine which week of the month a particular date falls into? The documentation for Moment js only seems to provide information on "week of year." For instance, if ...

waiting for a task to be carried out

Currently, I am working with a function called doSomething() which can be triggered by various DOM events. Is it feasible to listen not just for an event, but for the exact moment when this function is executed? To clarify - I am unable to modify the orig ...

positioned the div within the StickyContainer element to ensure it remains fixed in place

I've been working on making a div sticky in a React project. To achieve this, I added the react-sticky package to my project. I placed the div within the StickyContainer component as per the documentation. Although there are no visible errors, the sti ...

The most effective method for transforming an array into an object in JavaScript using a prefixed value as the key

I am working with an array that contains prefix values ["options_a", "options_b", "options_c", "capable_d", "capable_e_c" ] I am looking for a way to transform this array into an object format with the pre ...

Creating a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

What is the method to extract information from the provided URL?

Hello, I am looking to retrieve system requirements data from . How can I achieve this using JS or react? ...

Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database. I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to ...

Searching for data in Express JS with MongoDB using the $or operator is not possible

I am currently developing an API for managing my invoice data. Within this data, there are boolean values that determine the status of the invoices. For example, some invoices are marked as 'payment received', and I need to search for those speci ...

In search of a render function that can effectively apply styles to HTML strings using React JS

I have been struggling to convert the result field value, including HTML attributes string, into respective styles for one column in my antd table. Below is the string I am trying to convert: The exhaust air requirements for fume hoods will be based on m ...

Performing a MySQL query to select multiple rows and fields with the AND operator simultaneously

I've got a table: + --------------------------+---------------------------+--------------+--------+ | ID | SKU_ID | DKEY | DVAL | + --------------------------+---------------------------+----------- ...

What is the process for executing a function if the Materialize.css autocomplete feature is not chosen?

Is it feasible to create a function that triggers only when a user does not select an option from Materialize.css autocomplete feature? My goal is to automatically populate an email field with a predefined value based on the user's selection in anothe ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

Logging DOM elements with Electron's webview preload feature

Within my Electron program, I am utilizing a webview in my index.html file. The webview is equipped with a preloader, and my goal is to manipulate the DOM of the webview specifically, not just the index.html file. In my preloader code snippet below, the c ...

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Exploring ways to reach a specific digit level in JavaScript

As a newcomer to JavaScript, I've been searching online and trying different solutions but none have worked for me. Currently, I have a variable called num = 71.666666666 I'm looking to limit this number to 71.66 So far, I have attempted the f ...

In jQuery, apart from utilizing class, id, and text properties, what other methods can be used to pass a variable within an element?

Currently, I am facing a scenario where the class and id attributes are already assigned, but I need to pass a variable to jQuery. How should I go about this? Here is the HTML code: <input type="text" id="cannot_change_this" class="rather_ ...

What is the best way to erase the contents of a pop-up window?

Whenever I click on an event in the calendar, a popup window appears displaying textboxes and a list of items. The issue arises when I close the popup after selecting an event with items in the list; the same items show up for other events without refreshi ...