How do you check that a number is NaN in JavaScrip

2019-01-01 00:33发布

I’ve only been trying it in Firefox’s JavaScript console, but neither of the following statements return true:

parseFloat('geoff') == NaN;

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

29条回答
看淡一切
2楼-- · 2019-01-01 00:34

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

isNaN(any-Number);

For a generic approach which works for all the types in JS, we can use any of the following:

For ECMAScript-5 Users:

#1
if(x !== x) {
    console.info('x is NaN.');
}
else {
    console.info('x is NOT a NaN.');
}

For people using ECMAScript-6:

#2
Number.isNaN(x);

And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for 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.

查看更多
栀子花@的思念
3楼-- · 2019-01-01 00:37
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.

("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.

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 00:38

To fix the issue where '1.2geoff' becomes parsed, just use the Number() parser instead.

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:

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:

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".

查看更多
只若初见
5楼-- · 2019-01-01 00:38

marksyzm's answer works well, but it does not return false for Infinity as Infinity is techinicly not a number.

i came up with a isNumber function that will check if it is a number.

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));

查看更多
忆尘夕之涩
6楼-- · 2019-01-01 00:38

Simply convert the result to String and compare with 'NaN'.

var val = Number("test");
if(String(val) === 'NaN') {
   console.log("true");
}
查看更多
浮光初槿花落
7楼-- · 2019-01-01 00:39

NaN is a special value that can't be tested like that. An interesting thing I just wanted to share is this

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.

查看更多
登录 后发表回答