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

I have var a;

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

I need a condition that filters out all the values โ€‹โ€‹of a, so that only values> = 0 give the true value in the if condition.

What is the best way to achieve this, I don't want to use 3 different conditions related to using ||

+6
source share
7 answers

Oh ... But I really found ans .. it's that simple.

parseInt (null) = NaN.

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

0
source
 typeof x == "number" && x >= 0 

This works as follows:

  • null - typeof null == "object" , so the first part of the expression returns false
  • NaN - typeof NaN == "number" , but NaN not greater than, less than, or equal to any number, including itself, so the second part of the expression returns false
  • number - any other number greater than or equal to zero, the expression returns true
+7
source

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

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

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

+2
source

This works 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))}) 
+1
source

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

 if (a !== null && a >= 0) { ... } 
+1
source

My best solution to filter these values โ€‹โ€‹would be 2 conditions, and it looks like:

  if(a!=undefined && a>=0){ console.log('My variable is filtered out.') } 

I am not sure, but there is no single condition for its use.

+1
source

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

 if($.isNumeric(a) && a >= 0) 
0
source

Source: https://habr.com/ru/post/944693/


All Articles