我总是必须在没有任何东西的else条件中置null。有办法解决吗?

例如,

condition ? x = true : null;

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

condition ? x = true;

现在它显示为语法错误。

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

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

当前回答

要在数组或对象声明中使用三元操作符而不使用else,你可以使用ES6展开操作符…():

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

对于对象:

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

原始来源

其他回答

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

然而,对于你的例子,你可以这样做:

if(condition) x = true;

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

if(condition) { x = true; }

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

if(!defaults.slideshowWidth)
    { defaults.slideshowWidth = obj.find('img').width()+'px'; }
var x = condition || null;

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

设x为要测试的逻辑表达式,z为当x为真时要返回的值。你可以这样写:

y == x && z

如果x为真,y的结果为z,如果x为假,y也是。

简单的方法是:

if (y == x) z;

你可以这样写

x = condition ? true : x;

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

这就等于

if (condition) x = true

编辑:

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

有几个选择——我不是说这些更好/更坏——只是选择

传入null作为第三个参数可以工作,因为现有值为空。如果您重构并更改条件,那么就会有这种情况不再成立的危险。在三元中传入现有值作为第二个选择可以防止这种情况:

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

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

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