簡體   English   中英

無法在JavaScript中干燥簡寫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');

她是>>>我的傻瓜<<<對此有任何想法嗎? 謝謝..

實際上,這是使用此簡短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'導致'none' ,但是'anything_else' || 'none' 'anything_else' || 'none'導致'anything_else'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM