本文介绍了如何在JavaScript中设置默认布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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'

之所以有效,是因为colorundefined,而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 || truetrue,但是如您所见,它对于myOtherCar不起作用,因为false || truetrue.更改顺序无济于事,因为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. (其他虚假的值,包括nullundefined,将导致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中设置默认布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 03:18