问题描述
在JavaScript中设置默认的可选值通常是通过||
字符
Setting default optional values in JavaScript is usually done via the ||
character
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'
之所以有效,是因为color
是undefined
,而undefined || String
始终是String
.当然,围绕String || undefined
起作用的另一种方法是String
.当出现两个Strings
时,第一个获胜者'this' || 'that'
是'this'
.反之亦然,因为'that' || 'this'
是'that'
.
That works because color
is undefined
and undefined || String
is always the String
. Of course that also works the other way around String || undefined
is String
. When two Strings
are present the first one wins 'this' || 'that'
is 'this'
. It does NOT work the other way around as 'that' || 'this'
is 'that'
.
问题是:如何使用布尔值实现相同的目标?
The question is: How can I achieve the same with boolean values?
以下面的示例为例
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 || true
是true
,但是如您所见,它对于myOtherCar
不起作用,因为false || true
是true
.更改顺序无济于事,因为true || false
仍然是true
.
For myCar
it works because undefined || true
is true
but as you can see it does NOT work for myOtherCar
because false || true
is true
. Changing the order doesn't help as true || false
is still true
.
因此,我是否在这里遗漏了某些东西,或者以下是设置默认值的唯一方法吗?
Therefore, am I missing something here or is the following the only way to set the default value?
this.hasWheels = (hasWheels === false) ? false: true
干杯!
推荐答案
您可以执行以下操作:
this.hasWheels = hasWheels !== false;
这将为您提供一个true
值,除非hasWheels
是显式的false
. (其他虚假的值,包括null
和undefined
,将导致true
,我认为这是您想要的.)
That gets you a true
value except when hasWheels
is explicitly false
. (Other falsy values, including null
and undefined
, will result in true
, which I think is what you want.)
这篇关于如何在JavaScript中设置默认布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!