JavaScript 单行“if”语句 - 最佳语法,此替代方案?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8860654/
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
JavaScript single line 'if' statement - best syntax, this alternative?
提问by David Hobs
It's been clearly put, although opinion none the less, that forgoing curly brackets on a single line if
statement is not ideal for maintainability and readability.
已经清楚地表明,尽管意见仍然如此,在单行if
语句中放弃大括号对于可维护性和可读性来说并不理想。
But what about this?
但这又如何呢?
if (lemons) { document.write("foo gave me a bar"); }
It's even more compressed, and if expanded, the curly brackets won't be forgotten. Are there any blatant problems, and if not, what are the considerations? I feel like it's still very readable, at least as much as a ternary operator anyway. It seems to me like ternary operators aren't suggested as much due to readability, although I feel like that that conclusion isn't quite as unanimous.
它更加压缩,如果展开,则不会忘记大括号。有没有明显的问题,如果没有,有什么考虑?我觉得它仍然非常易读,至少和三元运算符一样好。在我看来,由于可读性,三元运算符的建议并不多,尽管我觉得这个结论并不完全一致。
The evil twin in me wants to suggest this, although the syntax obviously isn't meant for it, and is probably just a bad idea.
我心中的邪恶双胞胎想提出这个建议,尽管语法显然不是为了它,而且可能只是一个坏主意。
(syntax) ? document.write("My evil twin emerges"): "";
回答by Peter Olson
I've seen the short-circuiting behaviour of the &&
operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:
我已经看到了&&
用于实现此目的的运算符的短路行为,尽管不习惯这种方式的人可能会觉得难以阅读,甚至将其称为反模式:
lemons && document.write("foo gave me a bar");
Personally, I'll often use single-line if
without brackets, like this:
就个人而言,我会经常使用if
不带括号的单行,如下所示:
if (lemons) document.write("foo gave me a bar");
If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.
如果我需要添加更多语句,我会将语句放在下一行并添加括号。由于我的 IDE 会自动缩进,因此对这种做法的可维护性反对意见没有实际意义。
回答by asael2
I use it like this:
我像这样使用它:
(lemons) ? alert("please give me a lemonade") : alert("then give me a beer");
回答by Macro
You could use this format, which is commonly used in PHP:
您可以使用 PHP 中常用的这种格式:
(lemon) ? document.write("foo gave me a bar") : document.write("if condition is FALSE");
回答by shakee93
This one line is much cleaner.
这一行就干净多了。
if(dog) alert('bark bark');
I prefer this. hope it helps someone
我更喜欢这个。希望它可以帮助某人
回答by user3413838
// Another simple example
// 另一个简单的例子
var a = 11;
a == 10 ? alert("true") : alert("false");
回答by Mohideen bin Mohammed
can use this,
可以用这个
lemons ? alert("please give me a lemonade") : alert("then give me a beer");
explanation :
if lemons
exist then give me an alert("please give me a lemonade")
else
alert("then give me a beer")
解释:如果lemons
存在,那么给我一个alert("please give me a lemonade")
else
alert("then give me a beer")
回答by Kemacal
As a lot of people have said, if you're looking for an actual 1 line if then:
正如很多人所说,如果您正在寻找实际的 1 行,则:
if (Boolean_expression) do.something();
is preferred. However, if you're looking to do an if/else then ternary is your friend (and also super cool):
是首选。然而,如果你想做一个 if/else 那么三元是你的朋友(而且也超级酷):
(Boolean_expression) ? do.somethingForTrue() : do.somethingForFalse();
ALSO:
还:
var something = (Boolean_expression) ? trueValueHardware : falseATRON;
However, I saw one very cool example. Shouts to @Peter-Oslson for &&
但是,我看到了一个非常酷的例子。向@Peter-Oslson 大喊&&
(Boolean_expression) && do.something();
Lastly, it's not an if statement but executing things in a loop with either a map/reduce or Promise.resolve() is fun too. Shouts to @brunettdan
最后,它不是 if 语句,而是使用 map/reduce 或 Promise.resolve() 在循环中执行事物也很有趣。向@brunettdan 大喊大叫
回答by Marc
As has already been stated, you can use:
如前所述,您可以使用:
&& style
&& 风格
lemons && document.write("foo gave me a bar");
or
或者
bracket-less style
无支架样式
if (lemons) document.write("foo gave me a bar");
short-circuit return
短路返回
If, however, you wish to use the one line if
statement to short-circuit a function though, you'd need to go with the bracket-lessversion like so:
但是,如果您希望使用单行if
语句来短路函数,则需要使用无括号的版本,如下所示:
if (lemons) return "foo gave me a bar";
as
作为
lemons && return "foo gave me a bar"; // does not work!
will give you a SyntaxError: Unexpected keyword 'return'
会给你一个 SyntaxError: Unexpected keyword 'return'
回答by Anita Graham
I've seen many answers with many votes advocating using the ternary operator. The ternary is great if a) you do have an alternative option and b) you are returning a fairly simple value from a simple condition. But...
我已经看到很多答案,其中有很多人赞成使用三元运算符。如果 a) 您确实有替代选项并且 b) 您从一个简单的条件中返回一个相当简单的值,则三元是很棒的。但...
The original question didn't have an alternative, and the ternary operator with only a single (real) branch forces you to return a confected answer.
最初的问题没有替代方案,只有一个(真实)分支的三元运算符迫使您返回一个完美的答案。
lemons ? "foo gave me a bar" : "who knows what you'll get back"
lemons ? "foo gave me a bar" : "who knows what you'll get back"
I think the most common variation is lemons ? 'foo...' : ''
, and, as you'll know from reading the myriad of articles for any language on true, false, truthy, falsey, null, nil, blank, empty (with our without ?) , you are entering a minefield (albeit a well documented minefield.)
我认为最常见的变体是lemons ? 'foo...' : ''
,而且,正如您通过阅读有关 true、false、truthy、falsey、null、nil、blank、empty (with our without ?) 的任何语言的无数文章而知道的,您正在进入一个雷区(尽管有据可查的雷区。)
As soon as any part of the ternary gets complicated you are better off with a more explicit form of conditional.
一旦三元的任何部分变得复杂,您最好使用更明确的条件形式。
A long way to say that I am voting for if (lemons) "foo"
.
很长的路要说我投票支持if (lemons) "foo"
.
回答by brunettdan
Example in arrow functions:
箭头函数示例:
let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)
In promises:
在承诺中:
Promise.resolve()
.then(_=>checkTrueFalse && asyncFunc())
.then(_=>{ .. })
Otherwise:
除此以外:
if(somethingTrue) thenDo()
If it's just a simple conditional, I prefer using if(value)whenever possible because the word ifin the beginning of the statement says more about what's happening than paranthesis and questionmarks.
如果它只是一个简单的条件,我更喜欢尽可能使用if(value)因为语句开头的单词if比括号和问号更能说明正在发生的事情。