JavaScript中的三元运算符没有“Else” [英] Ternary Operators in JavaScript Without an "Else"
问题描述
我总是不得不在没有任何东西的其他条件下放入 null
。不管怎么说呢?例如,
I've always had to put null
in the else conditions that don't have anything. Is there anyway around it? E.g.
condition ? x = true : null;
基本上,还有办法:
condition ? x = true;
现在它显示为语法错误
仅供参考,这里有一些真实的示例代码:
FYI, here is some real example code:
!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;
推荐答案
首先,三元表达式不是替代品对于if / else构造 - 它等同于返回值的if / else构造。也就是说,if / else子句是代码,三元表达式是表达式,这意味着它返回一个值。
First of all, a ternary expression is not a replacement for an if/else construct - its an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
这意味着几个事情:
- 只有在
= $ c左侧有变量时才使用三元表达式$ c>指定返回值
- 当返回的值是两个值之一时使用三元表达式(或者如果合适则使用嵌套表达式)
- 表达式的每个部分(在?之后?之后)应该返回一个没有副作用的值(表达式
x = true
返回true,因为全部表达式返回最后一个值,但也会更改x,而x不会对返回的值产生任何影响)
- use ternary expressions only when you have a variable on the left side of the
=
that is to be assigned the return value - only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
- each part of the expression (after ? and after : ) should return a value without side effects (the expression
x = true
returns true as all expressions return the last value, but also changes x without x having any effect on the returned value)
简而言之 - '正确'使用三元表达式是
In short - the 'correct' use of a ternary expression is
var resultofexpression = conditionasboolean ? truepart: falsepart;
而不是您的示例条件? x = true:null;
,使用三元表达式设置 x
的值,你可以使用:
Instead of your example condition ? x=true : null ;
, where you use a ternary expression to set the value of x
, you can use this:
condition && (x = true);
这仍然是一个表达式,因此可能无法通过验证,因此更好的方法是
This is still an expression and might therefore not pass validation, so an even better approach would be
void(condition && x = true);
最后一个将通过验证。
但话又说回来,如果期望值是布尔值,只需使用条件表达式本身的结果
But then again, if the expected value is a boolean, just use the result of the condition expression itself
var x = (condition); // var x = (foo == "bar");
更新
关于你的样本,这可能更合适:
UPDATE In relation to your sample this is probably more appropriate:
defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
这篇关于JavaScript中的三元运算符没有“Else”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!