2012-03-05 36 views
4

我一直在尋找通過一些編譯咖啡腳本代碼,我發現了一些像下面,我以爲是真的很奇怪:Javascript或和賦值運算符

var current, x = 8; 
current = this._head || (this._head = x); 

運行此之後,當前擁有的價值8.通過||來判斷邏輯運算符的作品,我會期待它先評估左邊。在左邊得到一個'undefined'之後,它移動到右邊,它將this._head賦值給8.然後返回true,但是這部分不重要?我不明白它是如何返回並影響「當前」變量的?任何幫助將不勝感激,謝謝!

+0

OH!我剛剛意識到我正在運算符優先級上掛掉。 ||操作員在任何值已分配給當前之前發生。我基本上想象當前= this._head在它周圍有括號。感謝大家! – elju 2012-03-05 11:44:11

回答

1

||運營商返回而不是true。也許它有助於說

current = this._head || (this._head = x) 

也可以寫成

current = this._head ? this._head : (this._head = x); 

current = this._head; 

if(!current) 
    current = this._head = x; 
0

您可以使用expresion

var current=this._head ? this._head : (this._head = x); 
1
  1. ||如果操作符是「truthy」,則返回左側,否則返回右側 - 不管其真實性如何。它不會轉換爲表達式爲布爾值true/false!
    • undefined || (this._head = x)返回右側
  2. 賦值運算符也返回一個值!
    • this._head = x返回8在上面的例子中
  3. 第一賦值運算符的值是8賦予變量current