This question already has answers here:
Can I write an if statement within a Javascript object when setting an attribute?

(5个答案)


5年前关闭。




我有一些逻辑,可以通过on/off切换(与else else/if)true/false,但是我想使其更加简洁,而不使用switch语句。理想情况下,if/else将被转换为短线。谢谢!!!
var properties = {};
var IsItMuted = scope.slideshow.isMuted();
if (IsItMuted === true) {
    properties['Value'] = 'On';
} else {
    properties['Value'] = 'Off';
}

最佳答案

您需要一个三元运算符:

properties['Value'] = (IsItMuted === true) ? 'On' : 'Off';
? :称为三元运算符,在表达式中使用时就像if/else一样。

09-30 13:37
查看更多