gpt4 book ai didi

JavaScript isNaN 函数

转载 作者:行者123 更新时间:2023-11-30 07:44:45 25 4
gpt4 key购买 nike

我正在使用 isNan 函数来检查输入的值是否为数字:

if(isNaN(num)) {
alert('I am not a number');
}
else {
//
}

但是,如果输入的值为“5748hh”,则它可以像数字一样理解并返回 false。怎么了?

最佳答案

来自 Mozilla MDN

When the argument to the isNaN function is not a number, the value is first coerced to a number. The resulting value is then tested to determine whether it is NaN. Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." The confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as IEEE-794 floating-point values. The function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an IEEE-794 'Not A Number' value?"

所以 alert(isNaN('45345ll')) 返回 true,因为它的值强制转换不同于 parseInt/parseFloat 转换。

例如

var num = false;
console.log(isNaN(num)); /* return false because the coerced value is 0 but */
console.log(parseInt(num, 10)); /* return isNaN */

可能由于 if 语句中缺少括号,您得到了意想不到的值

关于JavaScript isNaN 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8923119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com