将函数的默认参数设置为布尔值的正确方法

Proper way to set a function's default parameter to a boolean?

本文关键字:布尔值 方法 设置 函数 默认 参数      更新时间:2023-09-26

我有一个函数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;
<<p> 读函数/strong>
   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
         };
    };

谢谢

如果您希望使用假值,请使用typeof:

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

否则,如果这样做:

var x = x || true;

并传入false,则x的值为true

这是因为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;