繁体   English   中英

寻找一个简单的提示提示变量alert()作为字符串或数字

[英]Looking for a simple alert of prompt() variable as string or as a number

我的搜索非常简单,我想设置一个prompt()变量,然后检查typeof变量是否为字符串然后为alert(“这是字符串”),否则,如果为数字,则alert为数字,否则为其他警告。 我已经尝试过了,但是行不通...

var text = prompt("enter your name");

if(typeof text === "number"){

    alert("this is not a number");
}
 else if(typeof text ==="string"){

    alert("this is a string");                          

}
else{

    alert("anyway.. thanks to try");

}

如果用户输入响应(即使它为空,或者看起来像一个数字),那么来自prompt()的返回值的类型将始终为String;如果用户取消对话框,则返回null 它永远不是数字。

如果要确定用户是否输入了可以解释为数字的字符串,则完全是另一回事。 考虑:

if (!isNaN(parseFloat(text))) {
    alert("it's a number");
}

(但请注意,有一些与parseFloat()相关的警告;尤其是,它将忽略尾随的垃圾。例如, 123.45xyz被解析为123.45 。)

使用双等号而不是三等号,并且在检查typeof时,请在要检查的对象周围使用方括号。 同样,如果在第二种情况下,则使用else是个好主意。

您的第一个语句应为“这是一个数字”。 Prompt()将以字符串形式返回该值,因此第一个条件将始终为false。 您可以更改条件以改为使用isNan(text)。 其余代码的第一个条件看起来像这样,应该可以工作。 您可能永远不会达到最后一个条件。

var text = prompt("enter your name");
if (!isNaN(text)) {
    alert("this is a number");
} else if (typeof text === "string") {
    alert("this is a string");
} else {
    alert("anyway.. thanks to try");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM