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

例如,

condition ? x = true : null;

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

condition ? x = true;

现在它显示为语法错误。

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

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

当前回答

我们现在也有了“null coalescing operator”(??)。它的工作原理类似于“OR”操作符,但仅在左侧表达式为空或未定义时返回,对于其他假值则不返回。

例子:

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

其他回答

var x = condition || null;

我们现在也有了“null coalescing operator”(??)。它的工作原理类似于“OR”操作符,但仅在左侧表达式为空或未定义时返回,对于其他假值则不返回。

例子:

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

从技术上讲,它可以返回任何东西。 但是,我想说,对于一行,三元更容易输入,至少1个字符短,因此更快。

看起来吗?hasDriversLicense =真:0 if(看起来)hasDriversLicense =真

在你的情况下,我认为三元运算符是多余的。可以使用||和&&操作符将变量直接赋值给表达式。

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

将变成:

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

它更清晰,更“javascript”风格。

更多情况下,人们使用逻辑运算符来缩短语句语法:

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

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

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

这段代码将返回默认值。如果为默认值,则为slideshowWidth。slideshowWidth的值为true,否则为obj.find('img').width() + 'px'值。

有关详细信息,请参见逻辑运算符的短路计算。