[英]Problems with prompt js typeof
I have problems with check prompt data.我在检查提示数据时遇到问题。 I need to check, if the prompt data will be string, paragraph could show that data is not number.
我需要检查,如果提示数据是字符串,段落可能会显示数据不是数字。 But according to my code, when I enter string data, it shows me odd or even message, but not 'Not number'.
但是根据我的代码,当我输入字符串数据时,它向我显示奇数或偶数消息,而不是“非数字”。 What's can be wrong?
有什么问题? Thanks a lot!
非常感谢!
prompt()
always returns a string , use parseInt(prompt(), 10)
to convert it to a string (10 is the numeric base, eg.: 2 means its a binary number) prompt()
总是返回一个字符串,使用parseInt(prompt(), 10)
将其转换为字符串(10 是数字基数,例如:2 表示它是一个二进制数)
It will return either a number or a NaN
( N ot A N umber) value.它将返回一个数字或一个
NaN
(N OT A N棕土)值。
typeof(NaN) === 'number'
NaN === NaN
will result in false, use Number.isNaN
to check if the value of a variable is NaN NaN === NaN
将导致 false,使用Number.isNaN
检查变量的值是否为 NaN
if (!(a === b))
is the same as if (a !== b)
if (!(a === b))
与if (a !== b)
Please, next time post your code as text instead of a sharing print screen of it, so we can ctrl+c, ctrl+v it请下次将您的代码作为文本而不是它的共享打印屏幕发布,以便我们可以 ctrl+c, ctrl+v 它
Because your second if condition evaluates as:因为您的第二个 if 条件评估为:
!("nonsense" % 2 === 0)
!(NaN % 2 === 0)
!(NaN === 0)
!(false)
true
therefore it will always show Odd" for non numbers. Maybe you should validate your data before you use it. Additionally val
will always be of type "string", you might want to parse it properly:因此,对于非数字,它总是会显示奇数。也许您应该在使用之前验证您的数据。此外,
val
将始终是“字符串”类型,您可能希望正确解析它:
const num = parseInt(prompt("A number?"), 10);
if(isNaN(num)) {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.