2013-05-05 56 views
0

我有一個函數read()需要作爲布爾參數。如果false傳入 - read(false) - 它不應該運行一段代碼。它適用於以下三個變體,但我不確定它們之間的差異或者它是否重要?將函數的默認參數設置爲布爾值的正確方法?

但我不明白這些變化之間的差異。

所有這三種變化的工作。

this.first_time_here = first_time_here !== false; 
var first_time_here = first_time_here !== false; 
var first_time_here = first_time_here || false; 

讀功能

function read (first_time_here) { 

      var first_time_here = first_time_here !== false; 

      // check to see what the function thinks first_time_here is 
      console.log("first time here is: " + first_time_here); 
      if (typeof first_time_here === 'boolean') { 
      console.log('Yes, I am a boolean'); 
      } 

      if (first_time_here) { 
        // do something if true 

     }; 
    }; 

謝謝

回答

2

如果您期望falsey值,使用typeof

var x = typeof x !== 'undefined' ? x : false; 

否則,如果你這樣做:

var x = x || true; 

並通過falsex的值將爲true

+0

甜和明確的。感謝您的增加版本。我會用它來創建更強大的API。 – 2013-05-05 03:21:10

1

這是因爲在JavaScript中的概念自動轉換時,undefined值轉換爲false。因此三條線類似以確保變量first_time_herefalse,而不是undefined

如果first_time_hereundefined

first_time_here = undedined !== false -> first_time_here = false != false 
-> first_time_here = false; 

和:

first_time_here = undedined || false -> first_time_here = false || false 
-> first_time_here = false; 
+0

謝謝Cuong!你的答案也有幫助。我選擇了@Blender的答案,因爲他提供了另一個我沒有考慮過的選項。 ; d – 2013-05-05 03:22:13

相關問題