Skip to content Skip to sidebar Skip to footer

Why Is Isnan("1") False?

I'm trying to write a simple test for the input of a function to determine if all of the inputs are numbers or not. function numbers(){ for (var i = 0; i < arguments.length; i

Solution 1:

isNaN implicitly coerces the argument to Number, and then checks whether this coerced value is NaN. See http://es5.github.io/#x15.1.2.4

That is, isNaN(foo) is equivalent to isNaN(Number(foo))

Code fix:

if (typeofarguments[i] !== 'number' || isNaN(arguments[i])) returnfalse;

The second part of the condition is because typeof NaN === 'number'.


Your function might be a bit more readable in functional style, using ES5's Array#every method:

//returns whether all arguments are of type Number and not NaNfunctionnumbers() {
    return [].every.call(arguments, function(arg) {
        returntypeof arg === 'number' && !isNaN(arg);
    });
}

Solution 2:

isNan() will attempt to cast it to a number, and then check. I would use this instead

if(!isNaN(parseFloat(arguments[i])) && isFinite(arguments[i])){
    returnfalse;
}

Alternatively, if you're using jQuery, you could use its built-in $.isNumeric() function

Post a Comment for "Why Is Isnan("1") False?"