JavaScript 中没有“Else”的三元运算符

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

Ternary Operators in JavaScript Without an "Else"

javascriptoptimizationsyntax-error

提问by Oscar Godson

I've always had to put nullin the else conditions that don't have anything. Is there anyway around it? E.g.

我总是不得不放入null没有任何东西的 else 条件。反正周围有吗?例如

condition ? x = true : null;

basically, is there a way to do:

基本上,有没有办法做到:

condition ? x = true;

Now it shows up as a syntax error

现在它显示为语法错误

FYI, here is some real example code:

仅供参考,这是一些真实的示例代码:

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null;

回答by Sean Kinsey

First of all, a ternary expression is not a replacement for an if/else construct - its an equivalent to an if/else construct that returnsa value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

首先,三元表达式不是 if/else 结构的替代品——它等同于返回值的 if/else 结构。也就是说,if/else 子句是代码,三元表达式是表达式,意味着它返回一个值。

This mean several things:

这意味着几件事:

  • 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 = truereturns true as all expressions return the last value, but also changes x without x having any effect on the returned value)
  • 仅当您在左侧有一个=要分配返回值的变量时才使用三元表达式
  • 仅当返回值是两个值之一时才使用三元表达式(如果合适,则使用嵌套表达式)
  • 表达式的每个部分(在 ? 之后和 : 之后)都应该返回一个没有副作用的值(表达式x = true返回 true 因为所有表达式都返回最后一个值,但也会改变 x 而 x 对返回值没有任何影响)

In short - the 'correct' use of a ternary expression is

简而言之 - 三元表达式的“正确”使用是

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

代替您的 example condition ? x=true : null ;,您可以使用三元表达式来设置 的值x,您可以使用以下命令:

 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);

The last one will pass validation.

最后一个将通过验证。

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");


UPDATEIn relation to your sample this is probably more appropriate:

更新关于您的样本,这可能更合适:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

回答by In silico

No, it needs three operands. That's why they're called ternaryoperators.

不,它需要三个操作数。这就是为什么它们被称为三元运算符。

However, for what you have as your example, you can do this:

但是,对于您所拥有的示例,您可以这样做:

if(condition) x = true;

Although it's safer to have braces if you need to add more than one statement in the future:

如果将来需要添加多个语句,使用大括号会更安全:

if(condition) { x = true; }

Edit:Now that you mention the actual code in which your question applies to:

编辑:既然您提到了您的问题适用的实际代码:

if(!defaults.slideshowWidth)
    { defaults.slideshowWidth = obj.find('img').width()+'px'; }

回答by Eugene Tiurin

More often people get use of logical operators to shorten the statement syntax:

人们更多地使用逻辑运算符来缩短语句语法:

!defaults.slideshowWidth &&
  (defaults.slideshowWidth = obj.find('img').width()+'px');

But in your particular case the syntax can be even simpler

但是在您的特定情况下,语法可以更简单

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

This code will return the defaults.slideshowWidthvalue if the defaults.slideshowWidthis evaluated to true and obj.find('img').width()+'px'value otherwise.

defaults.slideshowWidth如果defaults.slideshowWidth被评估为真,则此代码将返回obj.find('img').width()+'px'值,否则返回值。

See the Short-Circuit Evaluationof logical operators for details.

有关详细信息,请参阅逻辑运算符的短路评估

回答by philfreo

var x = condition || null;

回答by mdma

You could write

你可以写

x = condition ? true : x;

So that x is unmodified when the condition is false.

所以当条件为假时 x 未被修改。

This then is equivalent to

这则相当于

if (condition) x = true

EDIT:

编辑:

!defaults.slideshowWidth 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : null 

There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives

有几个替代方案——我不是说这些更好/更糟——只是替代方案

Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:

将 null 作为第三个参数传递有效,因为现有值为 null。如果您重构并更改条件,则存在不再为真的危险。传入现有值作为三元中的第二个选择可防止这种情况:

!defaults.slideshowWidth = 
      ? defaults.slideshowWidth = obj.find('img').width()+'px' 
      : defaults.slideshowwidth 

Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write

更安全,但可能不那么好看,而且打字更多。在实践中,我可能会写

defaults.slideshowWidth = defaults.slideshowWidth 
               || obj.find('img').width()+'px'

回答by Yandiro

What about simply

简单的怎么样

    if (condition) { code if condition = true };

回答by Krasimir Kirilov

In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.

在您的情况下,我认为三元运算符是多余的。您可以使用 ||、&& 运算符将变量直接分配给表达式。

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;

will become :

会变成 :

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

It's more clear, it's more "javascript" style.

更清楚,它更像是“javascript”风格。

回答by fogx

To use a Ternary Operator without else inside of an array or object declaration you can use the ES6 spread operator ...()

要在数组或对象声明中使用没有 else 的三元运算符,您可以使用 ES6 扩展运算符 ...()

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

对于对象:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

original source

原始来源