你如何在 JavaScript 中检查一个数字是否为 NaN?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2652319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you check that a number is NaN in JavaScript?
提问by Paul D. Waite
I've only been trying it in Firefox's JavaScript console, but neither of the following statements return true:
我只在 Firefox 的 JavaScript 控制台中尝试过,但以下语句均不返回 true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
回答by chiborg
Try this code:
试试这个代码:
isNaN(parseFloat("geoff"))
For checking whether anyvalue is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
要检查任何值是否为 NaN,而不仅仅是数字,请参见此处:如何在 Javascript 中测试 NaN?
回答by Jazzy
I just came across this technique in the book Effective JavaScriptthat is pretty simple:
我刚刚在Effective JavaScript一书中发现了这种非常简单的技术:
Since NaN is the only JavaScript value that is treated as unequal to itself, you can always test if a value is NaN by checking it for equality to itself:
由于 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
Didn't realize this until @allsyed commented, but this is in the ECMA spec: https://tc39.github.io/ecma262/#sec-isnan-number
直到@allsyed 发表评论才意识到这一点,但这在 ECMA 规范中:https://tc39.github.io/ecma262/#sec-isnan-number
回答by rahul
Use this code:
使用此代码:
isNaN('geoff');
See isNaN()docs on MDN.
请参阅isNaN()MDN 上的文档。
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
回答by dopeddude
As far as a value of type Numberis to be tested whether it is a NaNor not, the global function isNaNwill do the work
至于要测试Number类型的值是否为 a NaN,全局函数isNaN将完成这项工作
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
对于适用于 JS 中所有类型的通用方法,我们可以使用以下任何一种:
For ECMAScript-5 Users:
对于 ECMAScript-5 用户:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
对于使用 ECMAScript-6 的人:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
并且为了在 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;
}
please check This Answerfor more details.
请查看此答案以获取更多详细信息。
回答by Jonathan Azulay
NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this
NaN 是一个特殊的值,不能像那样测试。我只想分享一个有趣的事情是这个
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
This returns true onlyfor NaN values and Is a safe way of testing. Should definitely be wrapped in a function or atleast commented, because It doesnt make much sense obviously to test if the same variable is not equal to each other, hehe.
这仅对NaN 值返回 true并且是一种安全的测试方式。肯定要包裹在一个函数中或者至少注释掉,因为测试同一个变量是否不相等显然没有多大意义,呵呵。
回答by Jerome WAGNER
回答by zangw
As of ES6, Object.is(..)is a new utility that can be used to test two values for absolute equality:
从ES6 开始,Object.is(..)是一个新的实用程序,可用于测试两个值的绝对相等性:
var a = 3 / 'bar';
Object.is(a, NaN); // true
回答by marksyzm
To fix the issue where '1.2geoff'becomes parsed, just use the Number()parser instead.
要解决'1.2geoff'被解析的问题,只需使用Number()解析器即可。
So rather than this:
所以而不是这个:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Do this:
做这个:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDIT: I just noticed another issue from this though... false values (and true as a real boolean) passed into Number()return as 0! In which case... parseFloat works every time instead. So fall back to that:
编辑:我刚刚注意到另一个问题...错误值(和真正的布尔值)传递给Number()return as 0!在这种情况下...... parseFloat 每次都有效。所以回到那个:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
And that covers seemingly everything. I benchmarked it at 90% slower than lodash's _.isNaNbut then that one doesn't cover all the NaN's:
这几乎涵盖了一切。我以比 lodash 慢 90% 的速度对其进行了基准测试,_.isNaN但是那个并没有涵盖所有的 NaN:
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Just to be clear, mine takes care of the human literal interpretation of something that is "Not a Number" and lodash's takes care of the computer literal interpretation of checking if something is "NaN".
需要明确的是,我的负责人对“非数字”的字面解释,而 lodash 负责检查某事是否为“NaN”的计算机字面解释。
回答by Ryan Griffith
While @chiborg 's answer IS correct, there is more to it that should be noted:
虽然@chiborg 的回答是正确的,但还有更多需要注意的地方:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Point being, if you're using this method for validation of input, the result will be rather liberal.
重点是,如果您使用这种方法来验证输入,结果将是相当宽松的。
So, yes you can use parseFloat(string)(or in the case of full numbers parseInt(string, radix)' and then subsequently wrap that with isNaN(), but be aware of the gotcha with numbers intertwined with additional non-numeric characters.
所以,是的,您可以使用parseFloat(string)(或者在完整数字的情况下parseInt(string, radix)' 然后随后用 包装它isNaN(),但要注意数字与其他非数字字符交织在一起的问题。
回答by SpYk3HH
Simple Solution!
简单的解决方案!
REALLY super simple! Here! Have this method!
真的超级简单!这里!有这个方法!
function isReallyNaN(a) { return a !== a; };
Use as simple as:
使用简单如:
if (!isReallyNaN(value)) { return doingStuff; }
See performance test hereusing this func vs selected answer
Also: See below 1st example for a couple alternate implementations.
查看here使用此 func 的性能测试vsselected answer
另外:请参阅下面的第一个示例以了解几个替代实现。
Example:
例子:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('.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>
There are a couple alternate paths you take for implementaion, if you don't want to use an alternately named method, and would like to ensure it's more globally available. WarningThese solutions involve altering native objects, and may not be your best solution. Always use caution and be aware that other Libraries you might use may depend on native code or similar alterations.
如果您不想使用交替命名的方法,并且希望确保它在全球范围内更可用,那么您可以采用几种替代路径来实现。警告这些解决方案涉及更改本机对象,可能不是您的最佳解决方案。始终谨慎使用并注意您可能使用的其他库可能依赖于本机代码或类似的更改。
Alternate Implementation 1: Replace Native isNaNmethod.
替代实现 1:替换 NativeisNaN方法。
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Object
*Suggested as it is also a poly-fill for ECMA 5 to 6
替代实现 2:附加到数字对象
*建议,因为它也是 ECMA 5 到 6 的 poly-fill
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Alternate solution test if empty
替代解决方案测试是否为空
A simple window method I wrote that test if object is Empty. It's a little different in that it doesn't give if item is "exactly" NaN, but I figured I'd throw this up as it may also be useful when looking for empty items.
我编写了一个简单的窗口方法来测试对象是否为Empty。它有点不同,因为如果 item 是“完全” 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);
})();
Example:
例子:
;(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('.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>
Extremely Deep Check If Is Empty
非常深入的检查是否为空
This last one goes a bit deep, even checking if an Object is full of blank Objects. I'm sure it has room for improvement and possible pits, but so far, it appears to catch most everything.
最后一个有点深入,甚至检查一个对象是否充满了空白对象。我确信它有改进的空间和可能的坑,但到目前为止,它似乎涵盖了大部分内容。
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('.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>

