[英]Does this === not work b/c of floating point rounding inaccuracies?
Let's say I have this snippet. 假设我有这个片段。
var age = prompt('what is your age?');
if (age === 30)
{
alert('your age is 30');
}
When I entered 30 in the prompt, the if statement doesn't trigger. 当我在提示中输入30时,if语句不会触发。 I suspect it has to do with floating point rounding errors, but don't really know for sure.
我怀疑这与浮点舍入错误有关,但并不确定。 Would be great to hear your thoughts on this.
很高兴听到您对此的想法。
window.prompt()
returns a string. window.prompt()
返回一个字符串。 A string is not identical to a number. 字符串与数字不同。 Use either of the following:
使用以下任一方法:
if (age === '30')
if (+age === 30) // Explicit type conversion
if (age == 30) // Implicit type conversion
For notes on the explicit conversion, see this answer . 有关显式转换的说明,请参见此答案 。 For example, An input of
00030
may also be valid. 例如,输入
00030
也可能有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.