Why is typeof x never 'number' when x comes from the prompt function?

前端 未结 4 1134
予麋鹿
予麋鹿 2020-11-29 13:09

I\'m having trouble getting the first function (below) to work correctly. I want it to ask for the age of the user with two possible outcomes. If the user enters the correct

4条回答
  •  無奈伤痛
    2020-11-29 13:34

    The other answers are showing you that prompt() (almost) always returns a string. You'll need to parseInt the response before you can check it for your age range. But I think your while-loop conditional is throwing you off. Also you need to parseInt() on the prompt a second time, inside your while loop. Try it like this:

    let age_entered = prompt("Enter Your Age:");
    age_entered = parseInt(age_entered); 
    
    while (age_entered <= 0 || Number.isNaN(age_entered)) {
       alert("You entered an incorrect value. Please enter correct age.");
       age_entered = prompt("Enter Your Age:");
       // do parseInt again
       age_entered = parseInt(age_entered); 
    }
    

    Notice we use Number.isNaN(age_entered). This is a more robust way to determine if a value is a number than comparing with typeof. See this doc here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

提交回复
热议问题