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

例如,

condition ? x = true : null;

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

condition ? x = true;

现在它显示为语法错误。

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

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

当前回答

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

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

其他回答

简单地说

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

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

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

为什么不写一个函数来避免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);

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

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

if(condition) x = true;

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

if(condition) { x = true; }

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

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