![](/img/trans.png)
[英]Javascript string replace weirdness — $$$$ gets collapsed to $$ — what's the reason behind this result?
[英]What's the reason to make a conditional without a result?
我遇到了這段代碼:
navigation.on('click', '.main-nav-item', function (e) {
var clickedNavItem = $j(this),
className = clickedNavItem.data('class'),
midNavItem = $j('.' + className, midNavigation);
midNavItem.length > 0 && e.preventDefault();
});
我試着理解最后一行的目的:
midNavItem.length > 0 && e.preventDefault();
如果midNavItem.Length> 0,它似乎停止了點擊,但我沒有遵守這個的語法。 它應該是_
if(midNavItem.length > 0) { e.preventDefault() };
不是兩個條件。
你為什么這樣寫?
它被稱為短路評估 。 你是對的 - 這是寫你建議的if
語句的另一種方式:
if (midNavItem.length > 0) {
e.preventDefault();
}
它的工作原理是因為&&
不會執行第二個操作數,除非第一個操作數是真的 。
使用它的基本原理通常是制作更整潔的代碼。 當然,這是主觀的。 可能有人說明確使用if
語法總是更好 - 但是你也會發現很多人/流行的庫使用簡寫。
它更短。
盡管在這種情況下,大量的空格會丟失“短促”。
這種優化只能通過縮小程序來完成, 而不是手動完成,因為它會降低代碼的可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.