如何在 JavaScript 中编写内联 IF 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10270351/
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
How to write an inline IF statement in JavaScript?
提问by takeItEasy
How can I use an inline if
statement in JavaScript? Is there an inline else
statement too?
如何if
在 JavaScript 中使用内联语句?也有内联else
语句吗?
Something like this:
像这样的东西:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
回答by MattW
You don't necessarily need jQuery. JavaScript alone will do this.
您不一定需要 jQuery。仅 JavaScript 就可以做到这一点。
var a = 2;
var b = 3;
var c = ((a < b) ? 'minor' : 'major');
The c
variable will be minor
if the value is true
, and major
if the value is false
.
该c
变量将是minor
如果该值true
,并且major
如果该值是false
。
This is known as a Conditional (ternary) Operator.
这称为条件(三元)运算符。
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
回答by undefined
For writing if
statement inline, the code inside of it should only be one statement:
if
内联写语句,里面的代码应该只有一个语句:
if ( a < b ) // code to be executed without curly braces;
回答by Mahmoud Gamal
There is a ternary operator, like this:
有一个三元运算符,如下所示:
var c = (a < b) ? "a is less than b" : "a is not less than b";
回答by Pebbl
You can also approximate an if/else using only Logical Operators.
您还可以仅使用逻辑运算符来近似 if/else。
(a && b) || c
The above is roughly the same as saying:
上面的内容大致等同于:
a ? b : c
And of course, roughly the same as:
当然,大致与以下相同:
if ( a ) { b } else { c }
I say roughly because there is one difference with this approach, in that you have to know that the value of b
will evaluate as true, otherwise you will always get c
. Bascially you have to realise that the part that would appear if () { here }
is now part of the condition that you place if ( here ) { }
.
我说粗略是因为这种方法有一个区别,即您必须知道 的值b
将评估为真,否则您将始终得到c
。基本上,您必须意识到将出现的部分if () { here }
现在是您放置的条件的一部分if ( here ) { }
。
The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:
由于 JavaScript 的传递/返回形成逻辑表达式的原始值之一的行为,上述情况是可能的,这取决于运算符的类型。某些其他语言,如PHP,进行运算的实际结果,即true 或false,即结果总是true 或false;例如:
14 && 0 /// results as 0, not false
14 || 0 /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4, not true
true && '' /// results as ''
{} || '0' /// results as {}
One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.
与普通的 if 语句相比,一个主要的好处是前两种方法可以在参数的右侧进行操作,即作为赋值的一部分。
d = (a && b) || c;
d = a ? b : c;
if `a == true` then `d = b` else `d = c`
The only way to achieve this with a standard if statement would be to duplicate the assigment:
使用标准 if 语句实现此目的的唯一方法是复制分配:
if ( a ) { d = b } else { d = c }
You may ask why use just Logical Operatorsinstead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure a
and b
were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.
你可能会问,为什么只使用逻辑运算符,而不是三元运算符,对于简单的情况下,你可能不会,除非你想确保a
和b
都是真实的。您还可以使用逻辑运算符实现更简化的复杂条件,使用嵌套的三元运算可能会变得非常混乱……如果您希望代码易于阅读,那么两者都不是那么直观。
回答by Onimusha
In plain English, the syntax explained:
用简单的英语,语法解释:
if(condition){
do_something_if_condition_is_met;
}
else{
do_something_else_if_condition_is_not_met;
}
Can be written as:
可以写成:
condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;
回答by HyderA
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
回答by Nahn
If you just want an inline IF (without the ELSE), you can use the logical AND operator:
如果您只想要一个内联 IF(没有 ELSE),您可以使用逻辑 AND 运算符:
(a < b) && /*your code*/;
If you need an ELSE also, use the ternary operation that the other people suggested.
如果您还需要 ELSE,请使用其他人建议的三元运算。
回答by Ivar
You could do like this in JavaScript:
你可以在 JavaScript 中这样做:
a < b ? passed() : failed();
回答by alan
FYI, you can compose conditional operators
仅供参考,您可以组合条件运算符
var a = (truthy) ? 1 : (falsy) ? 2 : 3;
If your logic is sufficiently complex, then you might consider using an IIFE
如果您的逻辑足够复杂,那么您可以考虑使用IIFE
var a = (function () {
if (truthy) return 1;
else if (falsy) return 2;
return 3;
})();
Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.
当然,如果你打算多次使用这个逻辑,那么你应该将它封装在一个函数中以保持良好和干燥。
回答by kurt
I often need to run more code per condition, by using: ( , , )
multiple code elements can execute:
我经常需要为每个条件运行更多代码,通过使用:( , , )
多个代码元素可以执行:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );