我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
当前回答
我创建了这个小函数,它就像一个咒语。 而不是检查NaN,这似乎是违反直觉的,你检查一个数字。我很确定我不是第一个这样做的人,但我想分享一下。
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
其他回答
使用以下代码:
isNaN('geoff');
参见MDN上的isNaN()文档。
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
似乎在Node.js中,isNaN()是不被开箱即用的。 我曾经和
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
我只想分享另一种选择,它不一定比这里的其他选择更好,但我认为它值得一看:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
这背后的逻辑是,除了0和NaN之外的所有数字都被转换为true。
我做了一个快速测试,它的性能和Number一样好。isNaN和as检查自身是否为false。这三个都比isNan表现得好
结果
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
如果您想避免损坏的isNaN函数,可能会很有用。
只要要测试类型为Number的值是否为NaN,全局函数isNaN将完成工作
isNaN(any-Number);
对于适用于JS中所有类型的通用方法,我们可以使用以下任何一种方法:
ECMAScript-5用户:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
对于使用ECMAScript-6的人:
#2
Number.isNaN(x);
为了在ECMAScript 5和6中保持一致性,我们也可以为Number.isNan使用这个填充
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
请查看这个答案了解更多细节。
你应该使用全局isNaN(value)函数调用,因为:
支持跨浏览器 有关文档,请参阅isNaN
例子:
isNaN('geoff'); // true
isNaN('3'); // false
我希望这对你有所帮助。