Check for NaN, null and >=0 in one condition

后端 未结 7 1824
一个人的身影
一个人的身影 2021-02-15 14:32

I have a var a;

Its value can be NaN, null and any +ve/-ve number including 0.

I require a condition which filters out all the values of a such that

相关标签:
7条回答
  • 2021-02-15 14:39

    I had the same problem some weeks ago, I solved it with:

    if(~~Number(test1)>0) {
      //...
    }
    

    http://jsfiddle.net/pT7pp/2/

    0 讨论(0)
  • 2021-02-15 14:39

    Ohk ...But i actually found the ans .. it is so Simple .

    parseInt(null) = NaN.

    So if(parseInt(a)>=0){} would do ...Yayyee

    0 讨论(0)
  • 2021-02-15 14:40

    This seems to work well:

    if (parseFloat(x) === Math.sqrt(x*x))...
    

    Test:

    isPositive = function(x) { return parseFloat(x) === Math.sqrt(x*x) }
    a = [null, +"xx", -100, 0, 100]
    a.forEach(function(x) { console.log(x, isPositive(x))})
    
    0 讨论(0)
  • 2021-02-15 14:46

    NaN is not >= 0, so the only exclusion you need to make is for null:

    if (a !== null && a >= 0) {
        ...
    }
    
    0 讨论(0)
  • 2021-02-15 14:50
    typeof x == "number" && x >= 0
    

    This works as follows:

    • null -- typeof null == "object" so first part of expression returns false
    • NaN -- typeof NaN == "number" but NaN is not greater than, less than or equal to any number including itself so second part of expression returns false
    • number -- any other number greater than or equal to zero the expression returns true
    0 讨论(0)
  • 2021-02-15 14:54

    Since you tagged jQuery, take a look at $.isNumeric()

    if($.isNumeric(a) && a >= 0)
    
    0 讨论(0)
提交回复
热议问题