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

发布于 2024-09-03 01:32:57 字数 355 浏览 4 评论 0原文

我总是不得不将 null 放在没有任何内容的 else 条件中。有办法解决吗?

例如,

condition ? x = true : null;

基本上,有没有办法执行以下操作?

condition ? x = true;

现在它显示为语法错误。

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

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

I've always had to put null in the else conditions that don't have anything. Is there a way around it?

For example,

condition ? x = true : null;

Basically, is there a way to do the following?

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

司马昭之心 2024-09-10 01:32:57

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

这意味着以下几点:

  • 仅当 = 左侧有一个要分配返回值的变量时才使用三元表达式
  • 仅当返回值是两个值之一时才使用三元表达式值(或者如果合适的话使用嵌套表达式)
  • 表达式的每个部分(在 ? 和 : 之后)应该返回一个没有副作用的值(表达式 x = true 返回 true,因为所有表达式都返回最后一个值,但它也会更改 x,而 x 对返回值没有任何影响)

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

var resultofexpression = conditionasboolean ? truepart: falsepart;

代替您的示例 condition ? x=true : null ;,当您使用三元表达式来设置 x 的值时,您可以使用:

 condition && (x = true);

这仍然是一个表达式,因此可能无法通过验证,因此更好的方法是

 void(condition && x = true);

最后一个将通过验证。

但话又说回来,如果预期值是布尔值,则只需使用条件表达式本身的结果

var x = (condition); // var x = (foo == "bar");

UPDATE

与您的示例相关,这可能更合适:

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

First of all, a ternary expression is not a replacement for an if/else construct - it's 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.

This means 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 = true returns true as all expressions return the last value, but it 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;

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

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

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
落日海湾 2024-09-10 01:32:57

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

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

if(condition) x = true;

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

if(condition) { x = true; }

编辑: 现在您提到了实际的代码您的问题适用于:

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

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

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'; }
镜花水月 2024-09-10 01:32:57

更常见的是,人们使用逻辑运算符来缩短语句语法:

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

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

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

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

请参阅短路评估< /a> 逻辑运算符的详细信息。

More often, people use 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.slideshowWidth value if the defaults.slideshowWidth is evaluated to true and obj.find('img').width() + 'px' value otherwise.

See Short-Circuit Evaluation of logical operators for details.

余生一个溪 2024-09-10 01:32:57
var x = condition || null;
var x = condition || null;
舂唻埖巳落 2024-09-10 01:32:57

我们现在还有“空合并运算符” (??)。它的工作原理与“OR”运算符类似,但仅在左侧表达式为 null 或未定义时返回它,对于其他虚假值则不会返回它。

例子:

const color = undefined ?? 'black';   // color: 'black'
const color = '' ?? 'black';   // color: ''
const color = '#ABABAB' ?? 'black';   // color: '#ABABAB'

We also have now the "Nullish coalescing operator" (??). It works similar to the "OR" operator, but only returns the left expression if it's null or undefined, it doesn't return it for the other falsy values.

Example:

const color = undefined ?? 'black';   // color: 'black'
const color = '' ?? 'black';   // color: ''
const color = '#ABABAB' ?? 'black';   // color: '#ABABAB'
无人问我粥可暖 2024-09-10 01:32:57

您可以

x = condition ? true : x;

这样写,以便当条件为假时 x 不会被修改。

这相当于

if (condition) x = true

编辑:

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

有几个替代方案 - 我并不是说这些更好/更差 - 只是替代方案

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

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

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

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

You could write

x = condition ? true : x;

So that x is unmodified when the condition is false.

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:

!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'
日暮斜阳 2024-09-10 01:32:57

简单点又怎么样

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

What about simply

    if (condition) { code if condition = true };
抹茶夏天i‖ 2024-09-10 01:32:57

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

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

对于对象:

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

原始来源

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

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

遮了一弯 2024-09-10 01:32:57

您可以考虑改用保护表达式(有关更多信息,请参阅 Michael Thiessen 的 优秀文章)。

x 为您要测试的逻辑表达式,z 为当 x 为 true 时您要返回的值。然后您可以这样写:

y == x && z

如果x 为真,y 的计算结果为z。如果x为假,则y也为假。

You might consider using a guard expression instead (see Michael Thiessen's excellent article for more).

Let x be a logical expression, that you want to test, and z be the value you want to return, when x is true. You can then write:

y == x && z

If x is true, y evaluates to z. And if x is false, so is y.

迷你仙 2024-09-10 01:32:57

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

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

会变得:

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

更清晰,更“javascript”风格。

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.

浴红衣 2024-09-10 01:32:57

为什么不编写一个函数来避免 else 条件呢?

这是一个例子:

const when = (statement, text) => (statement) ? text : null;

const math = when(1 + 2 === 3, 'Math is correct');
const obj = when(typeof "Hello Word" === 'number', "Object is a string");

console.log(math);
console.log(obj);

您还可以为任何对象实现该功能。以下是 string 类型的示例:

const when = (statement, text) => (statement) ? text : null;

String.prototype.if = when;

const msg = 'Hello World!';
const givenMsg = msg.if(msg.length > 0, 'There is a message! Yayyy!');
console.log(givenMsg);

Why not writing a function to avoid the else condition?

Here is an example:

const when = (statement, text) => (statement) ? text : null;

const math = when(1 + 2 === 3, 'Math is correct');
const obj = when(typeof "Hello Word" === 'number', "Object is a string");

console.log(math);
console.log(obj);

You could also implement that function for any objects. Here is an example for the type string:

const when = (statement, text) => (statement) ? text : null;

String.prototype.if = when;

const msg = 'Hello World!';
const givenMsg = msg.if(msg.length > 0, 'There is a message! Yayyy!');
console.log(givenMsg);

断肠人 2024-09-10 01:32:57

执行此操作的简单方法是:

if (y == x) z;

The simple way to do this is:

if (y == x) z;
清浅ˋ旧时光 2024-09-10 01:32:57

从技术上讲,它可以返回任何内容。
但是,我想说,对于单行,三元更容易键入,并且至少短 1 个字符,因此速度更快。

passTest?hasDriversLicense=true:0
if(passTest)hasDriversLicense=true

Technically, it can return anything.
But, I would say for a one liner the Ternary is easier to type and at least 1 character shorter, so therefore faster.

passTest?hasDriversLicense=true:0
if(passTest)hasDriversLicense=true

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文