What causes isNaN to malfunction?

This question already has an answer here:

  • Validate decimal numbers in JavaScript - IsNumeric() 48 answers

  • isNaN returns true if the value passed is not a number(NaN) (or if it cannot be converted to a number, so, null , true and false will be converted to 0 ), otherwise it returns false . In your case, you have to remove the ! before the function call!

    It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined , whose numerical value is NaN .

    You can't compare any value to NaN because it will never return false(even NaN === NaN ), I think that's because NaN is dynamically generated... But I'm not sure.

    Anyway you can fix your code by simply doing this:

    function isNumerical(value) {
        var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
        return isNum ? "<mark>numerical</mark>" : "not numerical";
    }
    

    Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"

    return isNum ? "not numerical" : "<mark>numerical</mark>";
    

    should be:

    return isNum ? "<mark>numerical</mark>" : "not numerical";
    

    See updated fiddle:

    http://jsfiddle.net/4nm7r/1/


    Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true , false and null :

    var isNum = !isNaN(parseFloat(value));
    

    Just keep in mind the following kinds of outputs from parseFloat :

    parseFloat("200$"); // 200
    parseFloat("200,100"); // 200
    parseFloat("200 foo"); // 200
    parseFloat("$200"); // NaN
    

    (ie, if the string starts with a number, parseFloat will extract the first numeric part it can find)

    链接地址: http://www.djcxy.com/p/26404.html

    上一篇: IsNumeric()与js类似的功能

    下一篇: 导致NaN故障的原因是什么?