JavaScript 中的一行 if/else

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

One line if/else in JavaScript

javascript

提问by Scott

I have some logic that switches(with and else/if) true/false with on/off but I would like to make is more condensed and not use a switch statement. Ideally the if/else would be converted into something that is one short line. Thank you!!!

我有一些逻辑可以用开/关来切换(用和其他/如果)真/假,但我想让它更简洁,而不是使用 switch 语句。理想情况下,if/else 将转换为一条短线。谢谢!!!

var properties = {};
var IsItMuted = scope.slideshow.isMuted();
if (IsItMuted === true) {
    properties['Value'] = 'On';
} else {
    properties['Value'] = 'Off';
}       

回答by elixenide

You want a ternary operator:

你想要一个三元运算符:

properties['Value'] = (IsItMuted === true) ? 'On' : 'Off';

The ? :is called a ternary operator and acts just like an if/elsewhen used in an expression.

? :被称为三元运算符,其作用就像一个if/else在表达式中使用时。

回答by scniro

You can likely replace your if/elselogic with the following to give you a "one-liner"

您可能可以用以下内容替换您的if/else逻辑,为您提供“单行”

properties['Value'] = scope.slideshow.isMuted() ? 'On' : 'Off';

see Conditional (ternary) Operatorfor more info

有关更多信息,请参阅条件(三元)运算符

回答by guest271314

var properties = {"Value":scope.slideshow.isMuted() && "on" || "off"}

回答by charlietfl

Combine all into one line.

全部合并为一行。

You don't need to create empty object, it can have properties and if brevity is what you want don't need the isItMutedeither

你并不需要创建空的对象,它可以有属性,如果简洁是你想要的东西不需要isItMuted任何

var properties = {Value : scope.slideshow.isMuted() ? 'On' : 'Off'};