javascript中不能DRY if-else(条件三元运算符)的简写

Cannot DRY short hand if-else (conditional ternary Operator) in javascript

本文关键字:运算符 三元 不能 DRY if-else 条件 javascript      更新时间:2023-09-26

我有一个简单的HTML页面,有一个按钮切换一个div,但一切都很好,但我有一个if-else语句在我的代码,像这样:

 if (info.style.display === '' || info.style.display == 'none'){
    info.style.display =  'inline-block';
} else {
     info.style.display =  'none';
}

我决定使用这样的简写语句;

 info.style.display === ''||info.style.display ==='none' ? info.style.display = 'inline-block' :info.style.display = 'none';

但仍然觉得时间太长,可能可以干燥,

嗯,我有两种方法,但都不是正确的方法:

// this solution works but requires two clicks first time run:
 info.style.display ==( ''||'none' ) ?info.style.display = 'inline-block' :info.style.display = 'none';

和:

 // this solution doesn't work:
  info.style.display == (''||'none' ? 'inline-block' : 'none');

Her is>>> My Plunker <<<有什么想法吗?谢谢你.>

实际上这是使用这个简短的if-else语句的正确方法

info.style.display = (info.style.display === '' || info.style.display === 'none') ? 'inline-block' : 'none'; 

因为你总是赋值,所以把条件语句放在右边;你也可以(如果你真的想)使用!info.style.display代替info.style.display == '':

info.style.display = !info.style.display || info.style.display === 'none' ? 'inline-block' : 'none';

或者甚至利用奇怪的强大的||运算符,虽然我不确定我会这样做:

info.style.display = (info.style.display || 'none') === 'none' ? 'inline-block' : 'none';

这是有效的,因为'' || 'none'导致'none',但'anything_else' || 'none'导致'anything_else'