Question

I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:

for (i = 0; i === tries; i += 1) {
    isSkipped = false;
    var guessedNumber = prompt("Guess your number now.");

    console.log("User guessed number " + guessedNumber);

    //check if number is correct
    if (guessedNumber === numberToGuess) {
        confirm("Hooray, you have guessed the number!");
        break;
    } else if (guessedNumber > numberToGuess) {
        confirm("A little too high...");
    } else {
        confirm("A little too low...");
    }
}

and here is the full code:

//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;

var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?

if (confirmPlay === true) {
    console.log("User wants to play");
} else {
    window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage

numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number

tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string

for (i = 0; i === tries; i += 1) {
    isSkipped = false;
    var guessedNumber = prompt("Guess your number now.");

    console.log("User guessed number " + guessedNumber);

    //check if number is correct
    if (guessedNumber === numberToGuess) {
        confirm("Hooray, you have guessed the number!");
        break;
    } else if (guessedNumber > numberToGuess) {
        confirm("A little too high...");
    } else {
        confirm("A little too low...");
    }
}

if (isSkipped === true) {
    console.log("Oh no! The for loop has been skipped!");
}

If you need any further details, just ask.

Was it helpful?

Solution 2

When you write:

for (i = 0; i === tries; i += 0) {

the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.

You should write:

for (i = 0; i < tries; i++) {

OTHER TIPS

Shouldn't the for be like this?:

for (i = 0; i < tries; i += 1) {

Also you need to use parseInt() function on user's input.

 var guessedNumber = parseInt(prompt("Guess your number now."), 10);

instead of

var guessedNumber = prompt("Guess your number now.");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top