Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

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

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 value (i.e an positive number) it should return the the age. On the other hand, if the user enters an incorrect value (string, null, undefined, negative number), it should display an alert message, and have the user repeat the process until a correct value is entered and returned.

function age_of_user() {
    let age_entered = prompt("Enter Your Age:"); 
    while (typeof age_entered !== "number" || age_entered < 0) {
       alert("You entered an incorrect value. Please enter correct age.");
       age_entered = 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...