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;
29 个解决方案
#1
420
Try this code:
试试这段代码:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
为了检查是否有任何值是NaN,而不是仅仅是数字,请参见这里:您如何用Javascript测试NaN ?
#2
104
I just came across this technique in the book Effective JavaScript that is pretty simple:
我刚刚在书中发现了这个技巧很简单:
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/# secisnan -number。
#3
42
Use this code:
使用这段代码:
isNaN('geoff');
See isNaN()
docs on MDN.
参见MDN上的isNaN()文档。
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
#4
30
As far as a value of type Number is to be tested whether it is a NaN
or not, the global function isNaN
will do the work
至于类型数的值是否为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 Answer for more details.
请查看此答案以了解更多细节。
#5
14
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 only for 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值,并且是一种安全的测试方法。应该用函数或至少注释来包装,因为如果相同的变量不相等,那么测试就没有多大意义了,呵呵。
#6
13
You should use the global isNaN(value)
function call, because:
您应该使用全局isNaN(值)函数调用,因为:
- It is supported cross-browser
- 它是跨浏览器支持
- See isNaN for documentation
- 看到isNaN文档
Examples:
例子:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
我希望这对你有帮助。
#7
7
As of ES6, Object.is(..)
is a new utility that can be used to test two values for absolute equality:
As of ES6, Object.is(..)是一种新的实用工具,可以用来测试绝对平等的两个值:
var a = 3 / 'bar';
Object.is(a, NaN); // true
#8
6
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(字符串)(或者在完整的数字parseInt(string, radix)的情况下),然后用isNaN()将它包装起来,但是要注意与其他非数字字符交织在一起的数字的gotcha。
#9
6
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()返回为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 _.isNaN
but 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”,那么计算机的字面解释就是检查。
#10
5
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 here using this func vs selected answer
在这里使用这个func vs选择的答案看性能测试。
Also: See below 1st example for a couple alternate implementations.
另外:请参见下面的第一个例子,了解一些备选实现。
Example:
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>
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. Warning These 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 isNaN
method.
// 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
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.
我编写了一个简单的窗口方法,测试对象是否为空。这有点不同,如果项目是“确切的”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('$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>
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('$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>
#11
4
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN
to make sure that the value is really NaN
.
如果您的环境支持ECMAScript 2015,那么您可能想要使用Number。isNaN要确保这个值真的是NaN。
The problem with isNaN
is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN的问题是,如果您使用非数字数据,那么将会使用一些令人困惑的规则(如每个MDN)。例如,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
因此,在ECMA脚本2015支持的环境中,您可能想要使用。
Number.isNaN(parseFloat('geoff'))
#12
3
I use underscore's isNaN
function because in JavaScript:
我使用下划线的isNaN函数,因为在JavaScript中:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
至少,要意识到这一点。
#13
2
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
似乎在节点中不支持isNaN()。js从盒子里出来。我在工作
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
#14
2
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
我只是想和大家分享另一种选择,它不一定比其他的更好,但我认为值得一看:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0
and NaN
are cast to true
.
这背后的逻辑是,除了0和NaN之外的每个数字都是正确的。
I've done a quick test, and it performs as good as Number.isNaN
and as checking against itself for false. All three perform better than isNan
我做了一个快速测试,它的性能和数字一样好。isNaN和检查自己是否为假。三者的表现都优于isNan。
The results
结果
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
May become useful if you want to avoid the broken isNaN
function.
如果您想避免破损的isNaN函数,可能会变得有用。
#15
2
NaN in JavaScript stands for "Not A Number", although its type is actually number.
NaN在JavaScript中表示“不是一个数字”,尽管它的类型实际上是Number。
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
为了检查变量是否为NaN,我们不能简单地使用函数isNaN(),因为isNaN()有以下问题:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
这里真正发生的是,myVar被隐含地强制到一个数字:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
它实际上是有意义的,因为A实际上不是一个数字。但是我们真正想要检查的是,如果myVar是value NaN。
So isNaN() cannot help. Then what should we do instead?
因此isNaN()不能帮助。那我们应该怎么做呢?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
在光中,NaN是唯一被处理的不平等的JavaScript值,所以我们可以使用!==来检查它的是否相等。
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
因此,如果真有一个变量!==本身,那么这个变量就是NaN的值:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
#16
1
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
相等运算符(== ==)不能用来测试对NaN的值。
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
看看Mozilla的文档,全球的NaN属性是一个表示非- numbe的值。
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
最好的方法是使用“isNaN()”来检查NaN。所有的浏览器都支持这种方式。
#17
1
The exact way to check is:
检查的准确方法是:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
#18
1
Maybe also this:
也许这个:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
#19
0
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
根据IEEE 754,所有涉及NaN的关系都是假的。因此,例如,(>= B) = false, (A <= B) = false,如果A或B或两者都是NaN。
#20
0
I wrote this answer to another question on * where another checks when NaN == null
but then it was marked as duplicate so I don't want to waste my job.
我在*的另一个问题上写了这个答案,当NaN == null时,会有另一个检查,但是它被标记为重复,所以我不想浪费我的工作。
Look at Mozilla Developer Network about NaN
.
看看关于NaN的Mozilla开发者网络。
Short answer
Just use distance || 0
when you want to be sure you value is a proper number or isNaN()
to check it.
当你想确定你的值是一个合适的数字或isNaN()时,只要使用|| 0就可以了。
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
当一些数学运算失败时,“NaN”(Not-a-Number)在javascript中是一个奇怪的全局对象。
You wanted to check if NaN == null
which results false
. Hovewer even NaN == NaN
results with false
.
您需要检查是否NaN == null,结果为false。Hovewer甚至NaN == NaN结果为false。
A Simple way to find out if variable is NaN
is an global function isNaN()
.
一个简单的方法来确定变量是否是NaN是一个全局函数isNaN()。
Another is x !== x
which is only true when x is NaN. (thanks for remind to @raphael-schweikert)
另一个是x !== x,只有当x是NaN时才成立。(感谢提醒@raphael-schweikert)
But why the short answer worked?
Let's find out.
让我们找出答案。
When you call NaN == false
the result is false
, same with NaN == true
.
当您调用NaN == false时,结果为false,与NaN == true相同。
Somewhere in specifications JavaScript has an record with always false values, which includes:
在规范JavaScript的某个地方,有一个总是错误值的记录,其中包括:
-
NaN
- Not-a-Number - 南-不是一个数字
-
""
- empty string - ”“——空字符串
-
false
- a boolean false - 错误——一个布尔错误。
-
null
- null object - 空-空对象
-
undefined
- undefined variables - 未定义,定义变量
-
0
- numerical 0, including +0 and -0 - 0 -数值0,包括+0和-0。
#21
0
Another solution is mentioned in MDN's parseFloat page
在MDN的parseFloat页面中提到了另一个解决方案。
It provides a filter function to do strict parsing
它提供了一个过滤器函数来进行严格的解析。
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
And then you can use isNaN
to check if it is NaN
然后你可以用isNaN来检查它是否是NaN。
#22
0
I've created this little function that works like a charm. Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
我创建了这个小函数,它很有魅力。你要检查一个数字,而不是检查似乎与直觉相反的NaN。我很确定我不是第一个这样做的人,但我想我应该分享。
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
#23
0
Found another way, just for fun.
找到另一种方法,只是为了好玩。
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
#24
0
marksyzm's answer works well, but it does not return false for Infinity
as Infinity is techinicly not a number.
marksyzm的答案工作得很好,但它不返回false,因为无穷大是techinicly而不是一个数字。
i came up with a isNumber
function that will check if it is a number.
我想出了一个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"));
UPDATE: i noticed that this code fails for some parameters, so i made it better.
更新:我注意到这段代码在某些参数上失败了,所以我做得更好了。
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));
#25
0
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
这不是优雅。但是在尝试了isNAN()之后,我到达了这个解决方案,这是另一个选择。在这个例子中,我也是允许的。“因为我是戴面具的。”您也可以将其反转以确保没有使用数字。
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
这是一个单独的字符评估,但是您也可以通过一个字符串循环来检查任何数字。
#26
0
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
#27
0
Is (NaN >= 0) ?...... "I don't Know".
(NaN >= 0) ?“我不知道”。
function IsNotNumber( i ){
if( i >= 0 ){ return false; }
if( i <= 0 ){ return false; }
return true;
}
Conditions only execute if TRUE.
条件只有在正确的情况下才会执行。
Not on FALSE.
不是假的。
Not on "I Don't Know".
不是“我不知道”。
#28
0
So I see several responses to this,
所以我看到了一些回应,
But I just use:
我只是使用:
function isNaN(x){
return x == x && typeof x == 'number';
}
#29
-1
Simply convert the result to String and compare with 'NaN'.
只需将结果转换为字符串,并与“NaN”进行比较。
var val = Number("test");
if(String(val) === 'NaN') {
console.log("true");
}
#1
420
Try this code:
试试这段代码:
isNaN(parseFloat("geoff"))
For checking whether any value is NaN, instead of just numbers, see here: How do you test for NaN in Javascript?
为了检查是否有任何值是NaN,而不是仅仅是数字,请参见这里:您如何用Javascript测试NaN ?
#2
104
I just came across this technique in the book Effective JavaScript that is pretty simple:
我刚刚在书中发现了这个技巧很简单:
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/# secisnan -number。
#3
42
Use this code:
使用这段代码:
isNaN('geoff');
See isNaN()
docs on MDN.
参见MDN上的isNaN()文档。
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
#4
30
As far as a value of type Number is to be tested whether it is a NaN
or not, the global function isNaN
will do the work
至于类型数的值是否为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 Answer for more details.
请查看此答案以了解更多细节。
#5
14
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 only for 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值,并且是一种安全的测试方法。应该用函数或至少注释来包装,因为如果相同的变量不相等,那么测试就没有多大意义了,呵呵。
#6
13
You should use the global isNaN(value)
function call, because:
您应该使用全局isNaN(值)函数调用,因为:
- It is supported cross-browser
- 它是跨浏览器支持
- See isNaN for documentation
- 看到isNaN文档
Examples:
例子:
isNaN('geoff'); // true
isNaN('3'); // false
I hope this will help you.
我希望这对你有帮助。
#7
7
As of ES6, Object.is(..)
is a new utility that can be used to test two values for absolute equality:
As of ES6, Object.is(..)是一种新的实用工具,可以用来测试绝对平等的两个值:
var a = 3 / 'bar';
Object.is(a, NaN); // true
#8
6
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(字符串)(或者在完整的数字parseInt(string, radix)的情况下),然后用isNaN()将它包装起来,但是要注意与其他非数字字符交织在一起的数字的gotcha。
#9
6
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()返回为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 _.isNaN
but 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”,那么计算机的字面解释就是检查。
#10
5
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 here using this func vs selected answer
在这里使用这个func vs选择的答案看性能测试。
Also: See below 1st example for a couple alternate implementations.
另外:请参见下面的第一个例子,了解一些备选实现。
Example:
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>
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. Warning These 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 isNaN
method.
// 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
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.
我编写了一个简单的窗口方法,测试对象是否为空。这有点不同,如果项目是“确切的”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('$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>
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('$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>
#11
4
If your environment supports ECMAScript 2015, then you might want to use Number.isNaN
to make sure that the value is really NaN
.
如果您的环境支持ECMAScript 2015,那么您可能想要使用Number。isNaN要确保这个值真的是NaN。
The problem with isNaN
is, if you use that with non-numeric data there are few confusing rules (as per MDN) are applied. For example,
isNaN的问题是,如果您使用非数字数据,那么将会使用一些令人困惑的规则(如每个MDN)。例如,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
So, in ECMA Script 2015 supported environments, you might want to use
因此,在ECMA脚本2015支持的环境中,您可能想要使用。
Number.isNaN(parseFloat('geoff'))
#12
3
I use underscore's isNaN
function because in JavaScript:
我使用下划线的isNaN函数,因为在JavaScript中:
isNaN(undefined)
-> true
At the least, be aware of that gotcha.
至少,要意识到这一点。
#13
2
It seems that isNaN() is not supported in Node.js out of the box.
I worked around with
似乎在节点中不支持isNaN()。js从盒子里出来。我在工作
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
#14
2
I just want to share another alternative, it's not necessarily better than others here, but I think it's worth looking at:
我只是想和大家分享另一种选择,它不一定比其他的更好,但我认为值得一看:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
The logic behind this is that every number except 0
and NaN
are cast to true
.
这背后的逻辑是,除了0和NaN之外的每个数字都是正确的。
I've done a quick test, and it performs as good as Number.isNaN
and as checking against itself for false. All three perform better than isNan
我做了一个快速测试,它的性能和数字一样好。isNaN和检查自己是否为假。三者的表现都优于isNan。
The results
结果
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
May become useful if you want to avoid the broken isNaN
function.
如果您想避免破损的isNaN函数,可能会变得有用。
#15
2
NaN in JavaScript stands for "Not A Number", although its type is actually number.
NaN在JavaScript中表示“不是一个数字”,尽管它的类型实际上是Number。
typeof(NaN) // "number"
To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:
为了检查变量是否为NaN,我们不能简单地使用函数isNaN(),因为isNaN()有以下问题:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
What really happens here is that myVar is implicitly coerced to a number:
这里真正发生的是,myVar被隐含地强制到一个数字:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.
它实际上是有意义的,因为A实际上不是一个数字。但是我们真正想要检查的是,如果myVar是value NaN。
So isNaN() cannot help. Then what should we do instead?
因此isNaN()不能帮助。那我们应该怎么做呢?
In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==
在光中,NaN是唯一被处理的不平等的JavaScript值,所以我们可以使用!==来检查它的是否相等。
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:
因此,如果真有一个变量!==本身,那么这个变量就是NaN的值:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
#16
1
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
Equality operator (== and ===) cannot be used to test a value against NaN.
相等运算符(== ==)不能用来测试对NaN的值。
Look at Mozilla Documentation The global NaN property is a value representing Not-A-Numbe
看看Mozilla的文档,全球的NaN属性是一个表示非- numbe的值。
The best way is using 'isNaN()' which is buit-in function to check NaN. All browsers supports the way..
最好的方法是使用“isNaN()”来检查NaN。所有的浏览器都支持这种方式。
#17
1
The exact way to check is:
检查的准确方法是:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
#18
1
Maybe also this:
也许这个:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
#19
0
According to IEEE 754, all relationships involving NaN evaluate as false except !=. Thus, for example, (A >= B) = false and (A <= B) = false if A or B or both is/are NaN.
根据IEEE 754,所有涉及NaN的关系都是假的。因此,例如,(>= B) = false, (A <= B) = false,如果A或B或两者都是NaN。
#20
0
I wrote this answer to another question on * where another checks when NaN == null
but then it was marked as duplicate so I don't want to waste my job.
我在*的另一个问题上写了这个答案,当NaN == null时,会有另一个检查,但是它被标记为重复,所以我不想浪费我的工作。
Look at Mozilla Developer Network about NaN
.
看看关于NaN的Mozilla开发者网络。
Short answer
Just use distance || 0
when you want to be sure you value is a proper number or isNaN()
to check it.
当你想确定你的值是一个合适的数字或isNaN()时,只要使用|| 0就可以了。
Long answer
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed.
当一些数学运算失败时,“NaN”(Not-a-Number)在javascript中是一个奇怪的全局对象。
You wanted to check if NaN == null
which results false
. Hovewer even NaN == NaN
results with false
.
您需要检查是否NaN == null,结果为false。Hovewer甚至NaN == NaN结果为false。
A Simple way to find out if variable is NaN
is an global function isNaN()
.
一个简单的方法来确定变量是否是NaN是一个全局函数isNaN()。
Another is x !== x
which is only true when x is NaN. (thanks for remind to @raphael-schweikert)
另一个是x !== x,只有当x是NaN时才成立。(感谢提醒@raphael-schweikert)
But why the short answer worked?
Let's find out.
让我们找出答案。
When you call NaN == false
the result is false
, same with NaN == true
.
当您调用NaN == false时,结果为false,与NaN == true相同。
Somewhere in specifications JavaScript has an record with always false values, which includes:
在规范JavaScript的某个地方,有一个总是错误值的记录,其中包括:
-
NaN
- Not-a-Number - 南-不是一个数字
-
""
- empty string - ”“——空字符串
-
false
- a boolean false - 错误——一个布尔错误。
-
null
- null object - 空-空对象
-
undefined
- undefined variables - 未定义,定义变量
-
0
- numerical 0, including +0 and -0 - 0 -数值0,包括+0和-0。
#21
0
Another solution is mentioned in MDN's parseFloat page
在MDN的parseFloat页面中提到了另一个解决方案。
It provides a filter function to do strict parsing
它提供了一个过滤器函数来进行严格的解析。
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
And then you can use isNaN
to check if it is NaN
然后你可以用isNaN来检查它是否是NaN。
#22
0
I've created this little function that works like a charm. Instead of checking for NaN which seems to be counter intuitive, you check for a number. I'm pretty sure I am not the first to do it this way, but I thought i'd share.
我创建了这个小函数,它很有魅力。你要检查一个数字,而不是检查似乎与直觉相反的NaN。我很确定我不是第一个这样做的人,但我想我应该分享。
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
#23
0
Found another way, just for fun.
找到另一种方法,只是为了好玩。
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
#24
0
marksyzm's answer works well, but it does not return false for Infinity
as Infinity is techinicly not a number.
marksyzm的答案工作得很好,但它不返回false,因为无穷大是techinicly而不是一个数字。
i came up with a isNumber
function that will check if it is a number.
我想出了一个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"));
UPDATE: i noticed that this code fails for some parameters, so i made it better.
更新:我注意到这段代码在某些参数上失败了,所以我做得更好了。
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));
#25
0
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
This is not elegant. but after trying isNAN() I arrived at this solution which is another alternative. In this example I also allowed '.' because I am masking for float. You could also reverse this to make sure no numbers are used.
这不是优雅。但是在尝试了isNAN()之后,我到达了这个解决方案,这是另一个选择。在这个例子中,我也是允许的。“因为我是戴面具的。”您也可以将其反转以确保没有使用数字。
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
This is a single character evaluation but you could also loop through a string to check for any numbers.
这是一个单独的字符评估,但是您也可以通过一个字符串循环来检查任何数字。
#26
0
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
#27
0
Is (NaN >= 0) ?...... "I don't Know".
(NaN >= 0) ?“我不知道”。
function IsNotNumber( i ){
if( i >= 0 ){ return false; }
if( i <= 0 ){ return false; }
return true;
}
Conditions only execute if TRUE.
条件只有在正确的情况下才会执行。
Not on FALSE.
不是假的。
Not on "I Don't Know".
不是“我不知道”。
#28
0
So I see several responses to this,
所以我看到了一些回应,
But I just use:
我只是使用:
function isNaN(x){
return x == x && typeof x == 'number';
}
#29
-1
Simply convert the result to String and compare with 'NaN'.
只需将结果转换为字符串,并与“NaN”进行比较。
var val = Number("test");
if(String(val) === 'NaN') {
console.log("true");
}