zem*_*rco 57 javascript boolean
在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'
Run Code Online (Sandbox Code Playgroud)
这工作,因为color
是undefined
和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 !!!!!!
Run Code Online (Sandbox Code Playgroud)
对于myCar
它的作品,因为undefined || true
是true
,但你可以看到它不工作了myOtherCar
,因为false || true
是true
.更改订单不帮助为true || false
仍然是true
.
因此,我在这里遗漏了什么或者以下是设置默认值的唯一方法吗?
this.hasWheels = (hasWheels === false) ? false: true
Run Code Online (Sandbox Code Playgroud)
干杯!
Ted*_*opp 118
你可以这样做:
this.hasWheels = hasWheels !== false;
Run Code Online (Sandbox Code Playgroud)
true
除非hasWheels
明确表示,否则会获得一个值false
.(其他有价值的值,包括null
和undefined
将导致true
,我认为这就是你想要的.)
怎么样:
this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;
Run Code Online (Sandbox Code Playgroud)
你的另一个选择是:
this.hasWheels = arguments.length > 0 ? hasWheels : true;
Run Code Online (Sandbox Code Playgroud)
从发布的答案中需要注意一些变化。
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'
Run Code Online (Sandbox Code Playgroud)
value1
value0
如果需要它是布尔假,则特别是从字符串 'false' 制作的。我发现这种放松有时很有用。value2
并且value3
是对原始发布答案的修改以保持一致性,不更改结果。value4
是 Babel 为默认参数编译的方式。 归档时间: |
|
查看次数: |
27160 次 |
最近记录: |