2013-05-05 79 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

相关问题