如何在JavaScript中使用内联if语句?也有内联else语句吗?

就像这样:

var a = 2;
var b = 3;

if(a < b) {
    // do something
}

当前回答

用简单的英语,语法解释如下:

if(condition){
    do_something_if_condition_is_met;
}
else{
    do_something_else_if_condition_is_not_met;
}

可以写成:

condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;

其他回答

除此之外,你还可以使用内联if条件和&&和||操作符。 像这样

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

如果你只是想要一个内联If(没有ELSE),你可以使用逻辑AND运算符:

(a < b) && /*your code*/;

如果还需要ELSE,则使用其他人建议的三元操作。

如果要内联编写if语句,其中的代码应该只有一条语句:

if ( a < b ) // code to be executed without curly braces;

我经常需要在每个条件下运行更多的代码,通过使用:(,,)多个代码元素可以执行:

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 ) );

用简单的英语,语法解释如下:

if(condition){
    do_something_if_condition_is_met;
}
else{
    do_something_else_if_condition_is_not_met;
}

可以写成:

condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;