1

I'm trying to compare the input from a prompt window to the position of the correct answer in an array within an array.

This function logs the question and possible answers to the console. It then logs the correct answer, but does not recognize the input as correct ie. it will always show the else statement. Code:

questionArray[randomQ].questionPrompt();
var currentQ = randomQ;   

Question.prototype.answerPrompt = function(){
  var tryQ = prompt("Enter number of the correct answer.");
    if (currentQ === tryQ){
      console.log('The correct answer is ' + this.answer)
    } else {
      console.log('Try again. ' + this.answer)
    }
   };

Console log. The final line comes after input of 0:

Question?
0) answer 0 - correct answer
1) answer 1
2) answer 2
Try again. 0

If I use

if (questionArray.answerArray[currentQ] === tryQ)

then the correct array item is found, and listed as undefined in a TypeError. How do I use that array item to compare to the prompt answer?

1 Answer 1

2

prompt will always return a string, so it won't be === to a number. Cast the prompt result to a number first.

You also probably want to exclude the empty string from defaulting to 0.

const guess = prompt("Enter number of the correct answer.");
const tryQ = guess && Number(guess);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I had many misadventures using Number(), had no idea it was so easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.