无法在 javascript 中 DRY 简写 if-else(条件三元运算符)

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

我有一个 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');

她是>>> My Plunker <<< 请问有什么想法吗? 谢谢..

既然你一直在赋值,就把条件放在右边;你也可以(如果你真的想)使用 !info.style.display 而不是 info.style.display == '':

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

甚至利用 curiously-powerful || operator 虽然我不确定我是否会这样做:

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

之所以有效,是因为 '' || 'none' 导致 'none',但 'anything_else' || 'none' 导致 'anything_else'

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

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