简体   繁体   English

无法在JavaScript中干燥简写if-else(条件三元运算符)

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

i have a simple page of html has a button toggles a div,, however all is working fine but i have an if-else statement in my code like this: 我有一个简单的html页面,有一个按钮可切换div,但是一切正常,但是我的代码中有一个if-else语句,如下所示:

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

I`m have decided to use short hand statement like so; 我决定像这样使用简短的陈述;

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

but still feeling thats too long and probably can be dried, 但仍然觉得那太久了,可能会晒干,

well, i have two approaches but each is not the right way: 好吧,我有两种方法,但是每种方法都不正确:

// this solution works but requires two clicks first time run:

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

and : 和:

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

Her is >>> My Plunker <<< Any idea on this please? 她是>>>我的傻瓜<<<对此有任何想法吗? Thank you.. 谢谢..

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

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

Since you're always assigning, just put the conditional on the right; 因为您一直在分配,所以只需将条件放在右边; you can also (if you really want to) use !info.style.display instead of info.style.display == '' : 您也可以(如果确实要使用)使用!info.style.display而不是info.style.display == ''

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

Or even taking advantage of the curiously-powerful || 甚至可以利用||强大的功能|| operator though I'm not sure I'd do it: 运算符,尽管我不确定是否会这样做:

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

That works because '' || 'none' 之所以有效,是因为'' || 'none' '' || 'none' results in 'none' , but 'anything_else' || 'none' '' || 'none'导致'none' ,但是'anything_else' || 'none' 'anything_else' || 'none' results in 'anything_else' . 'anything_else' || 'none'导致'anything_else'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM