javascript 在一种情况下检查 NaN、null 和 >=0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16477405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check for NaN, null and >=0 in one condition
提问by Bhumi Singhal
I have a var a;
我有一个 var a;
Its value can be NaN, null and any +ve/-ve number including 0.
它的价值可以是 NaN, null and any +ve/-ve number including 0.
I require a condition which filters out all the values of a such that only >=0 values yield a true in if condition.
我需要一个条件来过滤掉 a 的所有值,只有 >=0 的值在 if 条件下才会产生真值。
What is the best possible way to achieve this, I do not wish to use 3 different conditions joined using ||
实现这一目标的最佳方法是什么,我不希望使用 3 个不同的条件加入使用 ||
采纳答案by Bhumi Singhal
Ohk ...But i actually found the ans .. it is so Simple .
哦...但我实际上找到了答案 .. 太简单了。
parseInt(null) = NaN.
parseInt(null) = NaN。
So if(parseInt(a)>=0){}
would do ...Yayyee
所以if(parseInt(a)>=0){}
会做... Yayyee
回答by Salman A
typeof x == "number" && x >= 0
This works as follows:
其工作原理如下:
null
--typeof null == "object"
so first part of expression returns falseNaN
--typeof NaN == "number"
butNaN
is not greater than, less than or equal to any number including itself so second part of expression returns falsenumber
-- any othernumber
greater than or equal to zero the expression returns true
null
--typeof null == "object"
所以表达式的第一部分返回 falseNaN
--typeof NaN == "number"
但NaN
不大于、小于或等于包括自身在内的任何数字,因此表达式的第二部分返回 falsenumber
-- 任何其他number
大于或等于零的表达式返回真
回答by RobSky
I had the same problem some weeks ago, I solved it with:
几周前我遇到了同样的问题,我用以下方法解决了它:
if(~~Number(test1)>0) {
//...
}
回答by georg
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))})
回答by Alnitak
NaN
is not >= 0
, so the only exclusion you need to make is for null
:
NaN
不是>= 0
,因此您需要进行的唯一排除是null
:
if (a !== null && a >= 0) {
...
}
回答by Ahmet DAL
My best solution to filter those values out would be with 2 condition and it is like;
我过滤掉这些值的最佳解决方案是使用 2 个条件,就像;
if(a!=undefined && a>=0){
console.log('My variable is filtered out.')
}
I am not sure but there is no single condition usage to make it.
我不确定,但没有单一条件用法来实现它。
回答by Shikiryu
Since you tagged jQuery, take a look at $.isNumeric()
既然你标记了 jQuery,那么看看 $.isNumeric()
if($.isNumeric(a) && a >= 0)