skip to Main Content

I am trying to push the correct guess into an array and print out how many guesses it took (in this case one, cause I’m just inputting the correct one) and then printing out what that guess was, but I am continually getting array not defined.

var guesses = [];

function do_guess() {
  let guess = Number(document.getElementById("guess").value);
  let message = document.getElementById("message");
  if (guess == num) {
    guesses.push(guess)
    numguesses = array.length(guesses)
    message.innerHTML = "You got it! It took you " + numguesses + " tries and your guesses were " + guesses;
  }

2

Answers


  1. Problem is the way you try to count the number of guesses.

    array.length(guesses)
    

    Is not valid Javascript syntax.

    What happens is, the runtime thinks "array" must be something you forgot to define, since you try to call "length(guesses)" on it.

    Instead you should use the inbuilt property .lengthon guesses which is present on any array.

    Login or Signup to reply.
  2. The correct way of getting the number of elements inside an array in js :

    arrayInstance.length
    

    In your case it would be

     guesses.length
    

    Read more here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search