2010-07-02 63 views
11
the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach(); 

很明顯,這是無效的。注意「;」在appendTo()the_styles=null之間。我如何寫1行,仍然有像這樣的多個表達式?JavaScript中有多個表達式的三元運算符?

+0

只是一條建議:其他語言中的三元運算符不用於編寫完整的語句,而只用於表達式部分(即'='符號的右側部分)。在Java中,這首先無法編譯。最好不要養成這種習慣。 – FK82 2010-07-04 10:41:37

回答

19

使用逗號操作是這樣的:

the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles = $('.stylesheet').detach(); 

這裏是Mozilla開發者中心寫關於逗號操作:

當你想包括您可以用逗號需要單個表達式的位置中的多個表達式。該運算符最常用的用法是在for循環中提供多個參數。

在這裏閱讀更多:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

+0

這是一個非常整潔的形式,我也沒有想到大括號會如此深刻地改變陳述的含義。我不認爲我會寫這個,即使偶然,但比較'var x = 1,y = 2,z = 3;'和'var x =(1,y = 2,z = 3);'。在第一種情況下,'x'設置爲'1'。在第二種情況下,'x'設置爲'3'。這真的很乾淨。 – Andrew 2010-07-04 09:48:42

2
the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc> 

只是包裹代碼塊中(function() {})()

現在的困難部分:爲什麼你想這樣做?也許有更好的解決方案!

+1

是的,那是醜陋的,沒關係。我只是喜歡三元的,因爲它們很乾淨,只有一條線。 – 2010-07-02 18:25:16

+0

只要每個分支中的代碼是單個「行」,他們就很好。否則...使用多行! – mcherm 2010-07-02 20:23:14

1

我同意glowcoder但如果你仍然想它:

the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach(); 
+0

是的,我現在也是,謝謝! – 2010-07-02 18:27:21

0
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach(); 

你不需要空,如果您覆蓋它!

+0

我需要null,因爲如果不是,它會在初始點擊後保持相同的值,我需要一個「off/on」函數。 – 2010-07-02 18:24:48

0
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head'); 
+0

不工作...... :( – 2010-07-02 18:26:46

8

誰需要三元運算符?

​the_styles = !the_styles && $('.stylesheet').detach()​​​​ || 
      the_styles.appendTo('head') && null;​ 

不得不切換周圍另有所述第一表達將總是迫使第二表達.detach()null值的表達式來進行評估。

巧妙的代碼唯一的事情是,一旦你在咖啡休息之後回到它,即使對你來說它也沒有任何意義。所以這是更好的:

if(the_styles) { 
    the_styles.appendTo('head') 
    the_styles = null; 
} 
else { 
    the_styles = the_styles.detach('.stylesheet'); 
} 

對我來說,即使是上述簡單版本沒有任何意義。 什麼部分是顯而易見的,但爲什麼是這樣做的?

+0

+1 - 我有類似的答案,但誤讀了意圖。你是對的。 – user113716 2010-07-02 19:00:31

+1

@patrick - 我花了一段時間來評估短路,這總是一個尖叫的信號,不要試圖聰明:) – Anurag 2010-07-02 19:15:43