How do you check that a number is NaN in JavaScript?

前端 未结 30 2647
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:19

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

parseFloat(\'geoff\') == NaN;

parseFloat(\'ge         


        
30条回答
  •  感情败类
    2020-11-22 06:50

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

提交回复
热议问题