如何检查JavaScript中的数字是否为NaN?

我只是在Firefox的JavaScript控制台中尝试过,但是以下任何一条都不返回true:

parseFloat('geoff') == NaN;

parseFloat('geoff') == Number.NaN;

#1楼

我使用下划线的isNaN函数,因为在JavaScript中:

isNaN(undefined) 
-> true

至少要注意该陷阱。


#2楼

NaN是一个无法测试的特殊值。 我只想分享的一件有趣的事是

var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
    alert('nanValue is NaN');

仅对 NaN值返回true,这是一种安全的测试方法。 绝对应该将其包装在函数中或至少注释掉,因为测试同一个变量是否彼此不相等显然没有多大意义,呵呵。


#3楼

似乎开箱即用的Node.js不支持isNaN()。
我与

var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);

#4楼

我刚刚在《 有效JavaScript 》一书中遇到了这种技术,它很简单:

由于NaN是唯一被视为与自身不相等的JavaScript值,因此您始终可以通过检查其与自身的相等性来测试该值是否为NaN:

var a = NaN;
a !== a; // true 

var b = "foo";
b !== b; // false 

var c = undefined; 
c !== c; // false

var d = {};
d !== d; // false

var e = { valueOf: "foo" }; 
e !== e; // false

直到@allsyed发表评论才意识到这一点,但这在ECMA规范中: https ://tc39.github.io/ecma262/#sec-isnan-number


#5楼

尽管@chiborg的答案是正确的,但还有更多需要注意的地方:

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

重要的是,如果您使用此方法来验证输入,结果将是相当自由的。

扫描二维码关注公众号,回复: 9035640 查看本文章

因此,是的,您可以使用parseFloat(string) (或者在使用全数字的情况下,使用parseInt(string, radix) ',然后使用isNaN()将其包装起来,但要注意数字与其他非数字字符交织在一起的陷阱。


#6楼

要解决'1.2geoff'被解析的问题,只需使用Number()解析器即可。

所以而不是这样:

parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true

做这个:

Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true

编辑:我只是从中注意到了另一个问题……传递给Number() false值(和真实的布尔值)为0 ! 在这种情况下,parseFloat每次都起作用。 所以回到那个:

function definitelyNaN (val) {
    return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}

这似乎涵盖了所有内容。 我将其基准测试的速度比lodash的_.isNaN慢了90%,但随后并没有涵盖所有的NaN:

http://jsperf.com/own-isnan-vs-underscore-lodash-isnan

只是要清楚一点,我的是对“不是数字”的东西进行人类文字解释,而洛达德则是检查东西是否为“ NaN”的计算机文字解释。


#7楼

我只想分享另一种选择,它不一定比这里的其他更好,但是我认为值得研究:

function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }

其背后的逻辑是将除0NaN之外的每个数字都强制转换为true

我已经进行了快速测试,它的性能与Number.isNaN并且可以针对自身进行检查是否为假。 这三者的表现均优于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函数,可能isNaN


#8楼

您应该使用全局isNaN(value)函数调用,因为:

  • 支持跨浏览器
  • 有关文档,请参见isNaN

例子:

 isNaN('geoff'); // true
 isNaN('3'); // false

我希望这能帮到您。


#9楼

试试这个代码:

isNaN(parseFloat("geoff"))

要检查是否数值而不是数字而不是数字NaN,请参见此处: 如何在Javascript中测试NaN?


#10楼

使用此代码:

isNaN('geoff');

请参阅MDN上的isNaN()文档

alert ( isNaN('abcd'));  // alerts true
alert ( isNaN('2.0'));  // alerts false
alert ( isNaN(2.0));  // alerts false

#11楼

根据IEEE 754,除!=之外,所有涉及NaN的关系都评估为false。 因此,例如,如果A或B或两者均为NaN,则(A> = B)=假,(A <= B)=假。


#12楼

NaN === NaN;        // false
Number.NaN === NaN; // false
isNaN(NaN);         // true
isNaN(Number.NaN);  // true

相等运算符(==和===)不能用于针对NaN测试值。

查看Mozilla文档。全局NaN属性是一个表示Not-A-Numbe的值

最好的方法是使用内置函数“ isNaN()”来检查NaN。 所有浏览器都支持该方式。


#13楼

简单的解决方案!

真的超级简单! 这里! 有这个方法!

function isReallyNaN(a) { return a !== a; };

使用方法如下:

if (!isReallyNaN(value)) { return doingStuff; }

使用此功能与所选答案 在此处查看性能测试

另外:请参见下面的第一个示例,了解几个替代实现。


例:

 function isReallyNaN(a) { return a !== a; }; var example = { 'NaN': NaN, 'an empty Objet': {}, 'a parse to NaN': parseFloat('$5.32'), 'a non-empty Objet': { a: 1, b: 2 }, 'an empty Array': [], 'a semi-passed parse': parseInt('5a5'), 'a non-empty Array': [ 'a', 'b', 'c' ], 'Math to NaN': Math.log(-1), 'an undefined object': undefined } for (x in example) { var answer = isReallyNaN(example[x]), strAnswer = answer.toString(); $("table").append($("<tr />", { "class": strAnswer }).append($("<th />", { html: x }), $("<td />", { html: strAnswer }))) }; 
 table { border-collapse: collapse; } th, td { border: 1px solid; padding: 2px 5px; } .true { color: red; } .false { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table></table> 

如果您不想使用替代命名的方法,并且想确保该方法在全球范围内可用,那么您可以采用几种替代路径来实现。 警告这些解决方案涉及更改本机对象,可能不是最佳解决方案。 请务必谨慎,并注意您可能使用的其他库可能取决于本机代码或类似的更改。

替代实现1:替换本机isNaN方法。

//  Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }

替代实现2:附加到数字对象
*建议使用,因为它也是ECMA 5至6的填充料

Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
//  Use as simple as
Number.isNaN(NaN)

备用溶液测试(如果为空)

我编写了一个简单的窗口方法来测试object是否为Empty 。 有点不同,因为项目“是” NaN不会给出,但我认为我会把它扔掉,因为它在寻找空项目时也很有用。

/** isEmpty(varried)
 *  Simple method for testing if item is "empty"
 **/
;(function() {
   function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
   window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();

例:

 ;(function() { function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\\{\\}|\\[(null(,)*)*\\]/.test(JSON.stringify(a)); }; window.hasOwnProperty("empty")||(window.empty=isEmpty); })(); var example = { 'NaN': NaN, 'an empty Objet': {}, 'a parse to NaN': parseFloat('$5.32'), 'a non-empty Objet': { a: 1, b: 2 }, 'an empty Array': new Array(), 'an empty Array w/ 9 len': new Array(9), 'a semi-passed parse': parseInt('5a5'), 'a non-empty Array': [ 'a', 'b', 'c' ], 'Math to NaN': Math.log(-1), 'an undefined object': undefined } for (x in example) { var answer = empty(example[x]), strAnswer = answer.toString(); $("#t1").append( $("<tr />", { "class": strAnswer }).append( $("<th />", { html: x }), $("<td />", { html: strAnswer.toUpperCase() }) ) ) }; function isReallyNaN(a) { return a !== a; }; for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))}; 
 table { border-collapse: collapse; float: left; } th, td { border: 1px solid; padding: 2px 5px; } .true { color: red; } .false { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table> <table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table> 


极深检查是否为空

最后一个要深入一点,甚至检查对象是否充满空白对象。 我敢肯定它还有改进的余地和可能的缺陷,但是到目前为止,它似乎涵盖了大多数内容。

 function isEmpty(a) { if (!a || 0 >= a) return !0; if ("object" == typeof a) { var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\\{\\}|\\[(null(,)?)*\\]),?/g, '').replace(/"[^"]*":\\{\\},?/g, ''); if ( /^$|\\{\\}|\\[\\]/.test(b) ) return !0; else if (a instanceof Array) { b = b.replace(/(0|"0*"|false|null|\\{\\}|\\[(null(,)?)*\\]),?/g, ''); if ( /^$|\\{\\}|\\[\\]/.test(b) ) return !0; } } return false; } window.hasOwnProperty("empty")||(window.empty=isEmpty); var example = { 'NaN': NaN, 'an empty Objet': {}, 'a parse to NaN': parseFloat('$5.32'), 'a non-empty Objet': { a: 1, b: 2 }, 'an empty Array': new Array(), 'an empty Array w/ 9 len': new Array(9), 'a semi-passed parse': parseInt('5a5'), 'a non-empty Array': [ 'a', 'b', 'c' ], 'Math to NaN': Math.log(-1), 'an undefined object': undefined, 'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } }, 'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}] } for (x in example) { var answer = empty(example[x]), strAnswer = answer.toString(); $("#t1").append( $("<tr />", { "class": strAnswer }).append( $("<th />", { html: x }), $("<td />", { html: strAnswer.toUpperCase() }) ) ) }; function isReallyNaN(a) { return a !== a; }; for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))}; 
 table { border-collapse: collapse; float: left; } th, td { border: 1px solid; padding: 2px 5px; } .true { color: red; } .false { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table> <table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table> 


#14楼

如果您的环境支持ECMAScript 2015 ,则可能要使用Number.isNaN来确保该值确实是NaN

isNaN的问题是, 如果您将其与非数字数据一起使用,则几乎没有应用混乱的规则(按照MDN)。 例如,

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({});        // true

因此,在ECMA Script 2015支持的环境中,您可能需要使用

Number.isNaN(parseFloat('geoff'))

#15楼

只要要测试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的一致性,我们也可以将此polyfill用于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;
}

请检查此答案以获取更多详细信息。


#16楼

我将此答案写在StackOverflow上的另一个问题上,其中另一个检查了NaN == null但随后将其标记为重复,因此我不想浪费我的工作。

查看有关NaN Mozilla开发人员网络


简短答案

只需使用distance || 0 如果要确保您的值是一个正确的数字或isNaN()进行检查,则为distance || 0

长答案

NaN(非数字)是javascript中的一个怪异全局对象,在某些数学运算失败时经常返回。

您想检查NaN == null是否导致false 。 甚至NaN == NaN结果为false

找出变量是否为NaN简单方法是全局函数isNaN()

另一个是x !== x ,仅当x为NaN时才成立。 (感谢提醒@ raphael-schweikert)

但是为什么简短的答案行得通呢?

让我们找出答案。

当您调用NaN == false ,结果为false ,与NaN == true相同。

在规范的某个地方,JavaScript的记录始终为假值,其中包括:

  • NaN非数字
  • "" -空字符串
  • false布尔值false
  • null空对象
  • undefined -未定义的变量
  • 0数字0,包括+0和-0

#17楼

ES6开始Object.is(..)是一个新实用程序,可用于测试两个值的绝对相等性:

var a = 3 / 'bar';
Object.is(a, NaN); // true

#18楼

MDN的parseFloat页面中提到了另一种解决方案

它提供了过滤功能以进行严格的解析

var filterFloat = function (value) {
    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
      .test(value))
      return Number(value);
  return NaN;
}


console.log(filterFloat('421'));               // 421
console.log(filterFloat('-421'));              // -421
console.log(filterFloat('+421'));              // 421
console.log(filterFloat('Infinity'));          // Infinity
console.log(filterFloat('1.61803398875'));     // 1.61803398875
console.log(filterFloat('421e+0'));            // NaN
console.log(filterFloat('421hop'));            // NaN
console.log(filterFloat('hop1.61803398875'));  // NaN

然后可以使用isNaN来检查它是否为NaN


#19楼

确切的检查方法是:

//takes care of boolen, undefined and empty

isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'

#20楼

我创建了这个小功能,就像一个魅力。 您可以检查数字,而不是检查似乎反直观的NaN。 我很确定我不是第一个这样做的人,但我想我会分享的。

function isNum(val){
    var absVal = Math.abs(val);
    var retval = false;
    if((absVal-absVal) == 0){
        retval = true
    }

    return retval;
}

#21楼

只需将结果转换为String并与“ NaN”进行比较。

var val = Number("test");
if(String(val) === 'NaN') {
   console.log("true");
}

#22楼

找到了另一种方式,只是为了好玩。

function IsActuallyNaN(obj) {
  return [obj].includes(NaN);  
}

#23楼

marksyzm的答案效果很好,但是对于Infinity ,它不会返回false,因为从技术上讲Infinity不是数字。

我想出了一个isNumber函数,它将检查它是否为数字。

 function isNumber(i) { return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1; } console.log(isNumber(Infinity)); console.log(isNumber("asdf")); console.log(isNumber(1.4)); console.log(isNumber(NaN)); console.log(isNumber(Number.MAX_VALUE)); console.log(isNumber("1.68")); 

更新:我注意到该代码对于某些参数失败,所以我做得更好。

 function isNumber(i) {//function for checking if parameter is number if(!arguments.length) { throw new SyntaxError("not enough arguments."); } else if(arguments.length > 1) { throw new SyntaxError("too many arguments."); } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) { throw new RangeError("number cannot be \\xB1infinity."); } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) { throw new TypeError("parameter cannot be object/array."); } else if(i instanceof RegExp) { throw new TypeError("parameter cannot be RegExp."); } else if(i == null || i === undefined) { throw new ReferenceError("parameter is null or undefined."); } else { return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i); } } console.log(isNumber(Infinity)); console.log(isNumber(this)); console.log(isNumber(/./ig)); console.log(isNumber(null)); 


#24楼

alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);

这不优雅。 但是在尝试isNAN()之后,我得出了这个解决方案,这是另一种选择。 在此示例中,我还允许使用“。”。 因为我要掩盖浮标。 您也可以反向进行此操作以确保不使用任何数字。

("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)

这是一个单字符评估,但您也可以遍历字符串以检查是否有任何数字。


#25楼

 function isNotANumber(n) { if (typeof n !== 'number') { return true; } return n !== n; } 


#26楼

JavaScript中的NaN代表“不是数字”,尽管其类型实际上是数字。

typeof(NaN) // "number"

要检查变量的值是否为NaN,我们不能简单地使用isNaN()函数,因为isNaN()存在以下问题,请参见下文:

var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN

真正发生的是myVar被隐式强制为数字:

var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact

这实际上是有道理的,因为“ A”实际上不是数字。 但是,我们真正要检查的是myVar是否完全值NaN。

因此isNaN()无济于事。 那我们该怎么办呢?

鉴于NaN是唯一一个与自身不相等的JavaScript值,因此我们可以使用!==检查其与自己的相等性。

var myVar; // undefined
myVar !== myVar // false

var myVar = "A";
myVar !== myVar // false

var myVar = NaN
myVar !== myVar // true

因此可以得出结论 ,如果确实是一个变量!==本身,则该变量的确切值是NaN:

function isOfValueNaN(v) {
    return v !== v;
}

var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false

#27楼

(NaN> = 0)吗?……“ 我不知道 ”。

function IsNotNumber( i ){
    if( i >= 0 ){ return false; }
    if( i <= 0 ){ return false; }
    return true;
}

条件仅在TRUE时执行。

不是FALSE

不在“ 我不知道 ”上。


#28楼

因此,我对此有一些回应,

但我只用:

function isNaN(x){
     return x == x && typeof x == 'number';
}

#29楼

也许也是这样:

function isNaNCustom(value){
    return value.toString() === 'NaN' && 
           typeof value !== 'string' && 
           typeof value === 'number'
}

#30楼

规则是:

NaN != NaN

isNaN()函数的问题是在某些情况下它可能返回意外结果:

isNaN('Hello')      //true
isNaN('2005/12/12') //true
isNaN(undefined)    //true
isNaN('NaN')        //true
isNaN(NaN)          //true
isNaN(0 / 0)        //true

检查该值是否真的为NaN的更好方法是:

function is_nan(value) {
    return value != value
}

is_nan(parseFloat("geoff"))
发布了0 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104224433