这 === 是否不适用于浮点舍入不准确的 b/c

Does this === not work b/c of floating point rounding inaccuracies?

本文关键字:不准确 舍入 是否 不适用 适用于      更新时间:2023-09-26

假设我有这个片段。

var age = prompt('what is your age?');
if (age === 30)
{
alert('your age is 30');
}

当我在提示中输入 30 时,if 语句不会触发。我怀疑这与浮点舍入错误有关,但不确定。很高兴听到你对此的想法。

window.prompt()返回一个字符串。字符串不等同于数字。使用以下任一方法:

if (age === '30') 
if (+age === 30)  // Explicit type conversion
if (age == 30)    // Implicit type conversion

有关显式转换的说明,请参阅此答案。例如,00030的输入也可能有效。