Javascript 不大于 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27753511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:38:12  来源:igfitidea点击:

Javascript not greater than 0

javascriptif-statement

提问by fc123

How to check if the value is notgreater than 0in javascript?

如何检查值是否大于0javascript?

I tried

我试过

if(!a>0){}

But it's not working.

但它不起作用。

回答by Mureinik

You need a second set of brackets:

您需要第二组括号:

if(!(a>0)){}

Or, better yet "not greater than" is the same as saying "less than or equal to":

或者,更好的是“不大于”与说“小于或等于”相同:

if(a<=0){}

回答by Ben Green

Mureinik's answer is completely correct, but seeing as "understanding falsey values" is one of the more important, less intuitive parts of JavaScript, it's perhaps worth explaining a little more.

Mureinik 的回答是完全正确的,但将“理解错误值”视为 JavaScript 中更重要、更不直观的部分之一,也许值得多解释一下。

Without the second set of brackets, the statement to be evaluated

没有第二组括号,要评估的语句

!a>0

is actually evaluated as

实际上被评估为

(!a) > 0

So what does (!a) mean? It means, find the boolean truthiness of "a" and flip it; true becomes false and false becomes true. The boolean truthiness of "a" means - if a it have one of the values that is considered "false", then it is false. In all other instances, ie for all other possible values of "a", it is "true". The falsey values are:

那么 (!a) 是什么意思?这意味着,找到“a”的布尔真实性并翻转它;真变成假,假变成真。“a”的布尔真实性意味着 - 如果 a 它具有被认为是“假”的值之一,那么它是假的。在所有其他情况下,即对于“a”的所有其他可能值,它是“真”。错误值为:

false
0 (and -0)
"" (the empty string)
null
undefined
NaN (Not a Number - a value which looks like a number, but cannot be evaluated as one

So, if a has any of these values, it is false and !a is true If it has any other, it is true and therefore !a is false.

因此,如果 a 具有这些值中的任何一个,则它为假且 !a 为真 如果还有其他值,则为真,因此 !a 为假。

And then, we try to compare this to 0. And 0, as we know, can also be "false", so your comparison is either

然后,我们尝试将其与 0 进行比较。正如我们所知,0 也可以是“假”,因此您的比较是

if (true > false) {}

or

或者

if (false > false) {}

Seeing as neither true or false can ever actually be anything other than equal to false (they can't be greater or less than!), your "if" will always fail, and the code inside the brackets will never be evaluated.

看到 true 或 false 实际上不可能是等于 false 以外的任何东西(它们不能大于或小于!),您的“if”将始终失败,并且永远不会评估括号内的代码。

回答by Dave Newton

a <= 0or (less clearly, IMO) !(a > 0)

a <= 0或(不太清楚,IMO) !(a > 0)

The !operator is being applied to a, not the entire expression, so extra parentheses are necessary if you go the "not" route.

!操作被应用到a,而不是整个表情,让多余的括号是必需的,如果你去了“不”的路线。

回答by jjk_charles

If you are hell-bent on using the >symbol, just reverse the operators

如果您一心想使用>符号,只需反转运算符

if(0>a)

If acan also be equal to 0, then,

如果a也可以等于0,那么,

if(0>=a)