我在看这个Javascript类:||的用途是什么? []操作
'use strict';
class Account {
constructor(a, b, c) {
this.a = a
this.b = b || []
this.c = c || []
}
}
什么是b || []
说什么?
我在看这个Javascript类:||的用途是什么? []操作
'use strict';
class Account {
constructor(a, b, c) {
this.a = a
this.b = b || []
this.c = c || []
}
}
什么是b || []
说什么?
||
运算符返回它看到的第一个真y值。许多人会将此用作设置变量默认值的快捷方式,因为undefined
为false-y。这样做的问题是默认也将用于null
,false
,0
,NaN
和空字符串(所有这些可能实际上也可能不实际是有效值)。
在这种情况下,如果b
或c
是undefined
(或任何其它假Y值),和this.b
this.c
将被设置为[]
。
null'和''''-.- – CoderPi
@CodeiSir' - 我添加了'null'并且已经提到了空字符串。 –
这是从哪里来的? – Lasoloz
如果是b可以被评估为false,它会返回[],否则返回b – CoderPi
http://stackoverflow.com/questions/4576867/javascript-or-operator-with-a-undefinded-variable – epascarello