如何在JavaScript中使用内联if语句?也有内联else语句吗?
就像这样:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
如何在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;
其他回答
(条件)?expressionTrue: expressionFalse;
例子
int a=20, b=10;
if (a>b) {
cout << "a greater than b";
} else {
cout << "b greater than a";
}
你可以简单地写:
int a=20, b=10;
(a>b) ? cout << "a greater than b" : cout << "b greater than a";
Inline if在JavaScript中很简单,不需要大括号:
if (a < b) doSomething()
从技术上讲,你可以在同一行中有一个else,但它需要一个分号:
if (a < b) doSomething(); else doSomethingElse()
您的团队的编码标准可能不需要上面的示例。最重要的是你要遵循适合你的团队的惯例。就我个人而言,在许多情况下,我更喜欢if语句而不是三元语句,因为我发现它们更容易阅读。
如果要内联编写if语句,其中的代码应该只有一条语句:
if ( a < b ) // code to be executed without curly braces;
如果你只是想要一个内联If(没有ELSE),你可以使用逻辑AND运算符:
(a < b) && /*your code*/;
如果还需要ELSE,则使用其他人建议的三元操作。
这个问题本质上不是:我能写出下面的东西吗?
if (foo)
console.log(bar)
else
console.log(foo + bar)
答案是,是的,上面的内容可以翻译。
但是,在做以下事情时要小心
if (foo)
if (bar)
console.log(foo)
else
console.log(bar)
else
console.log(foobar)
请务必将模棱两可的代码用大括号括起来,因为上述代码将抛出异常(类似的排列将产生不希望看到的行为)。