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

前端 未结 4 1122
予麋鹿
予麋鹿 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:33

    As mentioned in the comments, the prompt() function always captures the input as a string, even when the input is a valid number. To check if it's a number, you can try to parse the returned string with parseInt(age_entered) (or parseFloat if you want to allow non-integer ages, although that'd seem odd to me), and if you get back a number, the input is good - if you get back NaN, it wasn't valid.

    Here's your script updated based on this understanding:

    function age_of_user() {
        let age_entered = parseInt(prompt("Enter Your Age:")); 
        while (Number.isNaN(age_entered) || age_entered <= 0) {
           alert("You entered an incorrect value. Please enter correct age.");
           age_entered = parseInt(prompt("Enter Your Age:"));
        }   
    return age_entered;
    }
    
    function confirm_age() {
        let age = age_of_user();
        if (age < 18) {
            alert("Sorry! You need to be an adult to view content.");
        }
        else {
            alert("Welcome to our site.");
        }
    }
    
    confirm_age();
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-29 13:36

    It's returning a string, and parseInt will save you:

    ... 
      let age = parseInt(age_of_user());    
    ...
    
    0 讨论(0)
  • 2020-11-29 13:47

    prompt() is always returning a string,

    Try parseInt(prompt("Enter Your Age:")).

    0 讨论(0)
提交回复
热议问题