在 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'
之所以可行,是因为 color
是 undefined
和 undefined || String
始终是 String
。当然,这也适用于 String || 的另一种方式undefined
是 String
。当出现两个 Strings
时,第一个胜出 'this' || 'that'
是 'this'
。它不作为 'that' || 反过来工作'this'
是 'that'
。
问题是:如何使用 boolean 值实现同样的效果?
举个例子
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
。
因此,我是不是遗漏了什么,或者以下是设置默认值的唯一方法吗?
this.hasWheels = (hasWheels === false) ? false: true
干杯!
最佳答案
你可以这样做:
this.hasWheels = hasWheels !== false;
除非 hasWheels
明确为 false
,否则这将为您提供 true
值。 (其他虚假值,包括 null
和 undefined
,将导致 true
,我认为这就是您想要的。)
关于javascript - 如何在 JavaScript 中设置默认 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464169/