JavaScript 中没有“else"的三元运算符 [英] Ternary operators in JavaScript without an "else"

查看:34
本文介绍了JavaScript 中没有“else"的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如

condition ? x = true : null;

基本上,有没有办法做到以下几点?

Basically, is there a way to do the following?

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 - 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.

这意味着几件事:

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

而不是您的示例 condition ?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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆