如何在JavaScript中设置默认布尔值?

66

在JavaScript中设置默认的可选值通常是通过使用||字符完成的。

var Car = function(color) {
  this.color = color || 'blue';
};

var myCar = new Car();
console.log(myCar.color); // 'blue'

var myOtherCar = new Car('yellow');
console.log(myOtherCar.color); // 'yellow'

这个方法有效是因为colorundefined,而undefined || String总是返回String。当然反过来也同样成立,String || undefined会返回String。当有两个Strings时,第一个会被选中,例如'this' || 'that'会返回'this'。但是反过来不起作用,'that' || 'this'会返回'that'

问题是:如何使用布尔值实现相同的效果?

看下面这个例子:

var Car = function(hasWheels) {
  this.hasWheels = hasWheels || true;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // ALSO true !!!!!!

对于myCar,它起作用是因为undefined || truetrue,但是正如您所看到的,它对于myOtherCar不起作用,因为false || truetrue。改变顺序也无济于事,因为true || false仍然为true

因此,我是否遗漏了什么?或者以下是设置默认值的唯一方法?

this.hasWheels = (hasWheels === false) ? false: true

干杯!

5个回答

142
你可以这样做:
this.hasWheels = hasWheels !== false;

只要hasWheels没有被明确设置为false,这将为您提供一个true值。(其他的假值,包括nullundefined,将导致true,我认为这正是您想要的。)


3
他不想使用 ||;这只是从对非布尔值使用 || 的惯例中带来的。我认为发布这个问题是因为 || 没有达到所需的效果。 - Ted Hopp
@minopret - 你会怎么做? - Ted Hopp
JavaScript对真值和假值的处理有些奇怪,此时我懒得整理需要调查JavaScript实际操作所需的东西。但在一个强类型语言中,位运算符适用于布尔型变量,我们可以使用 x = (x != false) 或者 x ^= false 来达到同样的效果。 - minopret
@minopret - 是的,这种奇怪的情况是!=!==之间差异的核心。不幸的是,JS没有^==运算符。(顺便说一句,在Java这样的强类型语言中,“按位运算符适用于布尔值”并不正确。例如,有两个^运算符:一个按位运算符适用于整数值,另一个逻辑运算符适用于布尔值。它们具有不同的语义。在像C这样不太强类型的语言中,情况就不同了,它实际上没有区分布尔值和整数值。) - Ted Hopp
15
这是一个很棒的技巧,在我的情况下,我希望未定义的参数默认为 false,所以我使用了 this.hasWheels = hasWheels === true - Ramtin Soltani
显示剩余3条评论

6
怎么样:
this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;

你的另一个选择是:
this.hasWheels = arguments.length > 0 ? hasWheels : true;

3
这段代码运行良好,但我建议使用 ? !!hasWheels 替代 ? hasWheels,以确保只分配 truefalse(而不是其他任何值)给 this.hasWheels 变量。 - Ted Hopp

5

需要注意的是,已发布答案中存在一些变化。

var Var = function( value ) {
    this.value0 = value !== false;
    this.value1 = value !== false && value !== 'false';
    this.value2 = arguments.length <= 0 ? true : arguments[0];
    this.value3 = arguments[0] === undefined ? true : arguments[0];
    this.value4 = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
};

                     value0   value1   value2        value3         value4
---------------------------------------------------------------------------
Var("")              true     true     true          true           true
Var("''")            true     true     ''            ''             ''
Var("0")             true     true     0             0              0
Var("'0'")           true     true     '0'           '0'            '0'
Var("NaN")           true     true     NaN           NaN            NaN
Var("'NaN'")         true     true     'NaN'         'NaN'          'NaN'
Var("null")          true     true     null          null           null
Var("'null'")        true     true     'null'        'null'         'null'
Var("undefined")     true     true     undefined     true           true
Var("'undefined'")   true     true     'undefined'   'undefined'    'undefined'
Var("true")          true     true     true          true           true
Var("'true'")        true     true     'true'        'true'         'true'
Var("false")         false    false    false         false          false
Var("'false'")       true     false    'false'       'false'        'false'
  • value1是专门为字符串'false'制作的value0,如果需要将其转换为布尔值false,则可以使用它。我发现这种放松有时很有用。
  • value2value3是原始发布答案的修改版本,以保持一致性,但结果没有改变。
  • value4是Babel编译默认参数的方式。

4
你可以在ECMA6中使用默认函数参数功能。目前,浏览器仍未完全支持ECMA6,但你可以使用babel并立即开始使用新特性。
因此,原始示例将变得非常简单:
// specify default value for the hasWheels parameter
var Car = function(hasWheels = true) {
  this.hasWheels = hasWheels;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // false

2
但是如果有人传递了一个假值(即空字符串),this.hasWheels 将被赋予该空字符串,而不是布尔值。可能需要添加 hasWheels = (typeof hasWheels === 'boolean') ? hasWheels : true; - Otman Bouchari

1

如果您想要默认值为true,可以这样做,没有太多的困惑。

this.hasWheels=typeof hasWheels === 'boolean'?hasWheels:true

如果您想要默认值为false

this.hasWheels=typeof hasWheels === 'boolean'?false


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接