Different ways to effectively utilize the indexOf method for verifying the presence of an element within an array

In this fun guessing game, I am testing to see if the color entered by the user is in the array list or not. But oddly enough, even when the correct color is input, it keeps saying that 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;
  }
}

Answer №1

Your logic in the check_guess function needs to be corrected:

function check_guess() {
  if (colors.indexOf(guess_input) === -1) { // The condition should check for -1 to indicate not found
    alert(
      "This is not a color from the list! Please pick a color from the list\n\n"
    );
    return false;
  }
  else return true; // Make sure to handle all cases to avoid infinite loops
}

Ensure that your conditional statement is correct and handles both scenarios appropriately.

Answer №2

In order to determine if the input is not included in the list, you should use == -1, rather than > -1.

  if (colors.indexOf(user_guess) == -1) {
    // the item was not located

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

If the LocalStorage value is empty, relocate to a different location

Upon login, I save the user value to session storage using: localStorage.setItem("user", something); Once logged in successfully, I redirect to a specific page with $location.path('/something'). On this page, I retrieve the user data with $scop ...

Terser is causing ng build --prod to fail

When I run ng build --prod on my Angular 7 application (which includes a C# app on the BE), I encounter the following error: ERROR in scripts.db02b1660e4ae815041b.js from Terser Unexpected token: keyword (var) [scripts.db02b1660e4ae815041b.js:5,8] It see ...

Using JQuery to dynamically set dropdown option values from a JSON object

I have an HTML code snippet: $.ajax({ type: "POST", url: "hanca/hanca_crud.php", dataType: 'json', data: { id_hanca: id_hanca, type: "detail_hanca" }, //detail_hanca success: function(data) { var teks = ""; $.each( ...

Make sure to use jQuery waterfall 'reflow' only once all the images have finished loading

Currently, I am utilizing jQuery waterfall to achieve a grid-style display on my website. To address the issue of images overlapping, I have enclosed the waterfall method within a .load() function like this: $(window).load(function(){ $('#buildcon ...

Ways to adjust brightness of a color using jquery

I have implemented color swatches and a slider to adjust the lightness and darkness of colors. I am seeking a way to change the lightness of the color based on the slider value. Here is what I have attempted: $("#darklight").slider({ range: "min", ...

What could be causing my function to exclude only the final element of the array when it returns?

My goal with the following code is to retrieve all items from item.children. However, I am puzzled as to why it's not returning the last item. After conducting multiple result logs and SQL verifications, I eventually pinpointed the issue in a specific ...

Display Text Using a Variety of HTML Styles

Is there a way to achieve the following setup: HTML: <p>ABC</p> Output: DEF I am inquiring about this because I need to create an email template that includes the HTML snippet must contain <p>${__VCG__VAL__FIRST_NAME}</p> (where ...

What is the best way to access the current webdriver instance using code?

Currently, I am in the process of creating an end-to-end test suite with Protractor. As Protractor is based on WebdriverJS, I am attempting to utilize some of its functionality. More specifically, my goal is to incorporate certain behaviors using Webdriv ...

How can I define a default value for a dynamic route or page in Nuxt.js?

Whenever a user accesses my site through a referral link, I aim for the URL to appear as follows: localhost:3000/<dynamic affiliate username>/home However, in cases where someone visits my site directly as a guest, I would prefer the URL to default ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...

"I'm looking for a solution on integrating Osano CookieConsent into my Next.js application. Can

I'm facing a bit of a challenge with incorporating the Osano Cookie Consent JavaScript plugin into my nextjs app. I've been attempting to set up the cc object by initializing it in the useEffect of my root landing page: const CC = require( " ...

Enhance Chart JS by adding scroll functionality for handling large amounts of data

I'm encountering an issue with chart js. When displaying thousands of entries in a single chart, the density makes it difficult to read. I am looking for a way to implement a scrollbar when the data surpasses a certain threshold (or when there is a sp ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Is there a way to incorporate tailwind classes into each react component when utilizing the map() function?

While working on a React Movie app, I encountered an issue with the tailwind class mx-auto. It was not applying properly to all items in the array; only the first element was affected. const MoviesList = () => { return( <div className=&a ...

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

Removing automatically assigned ID information in Firestore can be achieved by following these steps:

async created () { const sn = await db.collection('forms').get() sn.forEach(v => { const { title, content } = v.data() this.forms.push({ title, content, id: v.id }) console.log(v.id) }) }, del () ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...