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

例如,

condition ? x = true : null;

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

condition ? x = true;

现在它显示为语法错误。

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

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

当前回答

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

!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'值。

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

其他回答

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

这里有一个例子:

Const when =(语句,文本)=>(语句)?文本:null; const math =当(1 + 2 == 3,'数学是正确的'); const obj = when(typeof "Hello Word" === " number ", "Object is a string"); console.log(数学); console.log (obj);

你也可以为任何对象实现这个函数。下面是一个string类型的例子:

Const when =(语句,文本)=>(语句)?文本:null; String.prototype.if = when; const msg = 'Hello World!'; const givenMsg = msg.if长度> 0,'有消息!Yayyy !”); console.log (givenMsg);

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

!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'值。

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

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

例子:

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

要在数组或对象声明中使用三元操作符而不使用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) { code if condition = true };