当x来自提示函数时,为什么typeof x永远不会“编号”? [英] Why is typeof x never 'number' when x comes from the prompt function?

查看:98
本文介绍了当x来自提示函数时,为什么typeof x永远不会“编号”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让第一个功能(如下)正常工作。我希望它用两种可能的结果来询问用户的年龄。如果用户输入正确的值(即正数),则应返回年龄。另一方面,如果用户输入了错误的值(字符串,空,未定义,负数),它应显示警告消息,并让用户重复该过程,直到输入并返回正确的值。

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


推荐答案

如评论中所述, prompt()函数总是将输入捕获为字符串,即使输入是有效数字。要检查它是否为数字,您可以尝试使用 parseInt(age_entered)(或 parseFloat )解析返回的字符串你想允许非整数年龄,虽然这对我来说似乎很奇怪),如果你得到一个数字,输入是好的 - 如果你回来 NaN ,它是无效的。

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

这篇关于当x来自提示函数时,为什么typeof x永远不会“编号”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆