I know I can't do if (!obj.x)
because if obj.x
is 0
or ""
, it will be "truthy".
(我知道if (!obj.x)
不能执行if (!obj.x)
因为如果obj.x
为0
或""
,它将是“真实的”。)
Option 1: I could do if (obj.x === null || obj.x === undefined)
.
(选项1: if (obj.x === null || obj.x === undefined)
我可以做。)
Option 2: But could I just do if (obj.x == null)
?
(选项2:但是, if (obj.x == null)
我可以做吗?)
Just to be clear, I want a condition that is true when obj.x
is null
or undefined
, but false for any other value.
(为了清楚obj.x
,我想要一个条件,当obj.x
为null
或undefined
时为true,但对于其他任何值obj.x
false。)
According to the comments, both options are equivalent but option 2 is more clear.
(根据评论,这两个选项是等效的,但选项2更清晰。)
I agree.(我同意。)
EDIT:
(编辑:)
Someone pointed out that there are similar questions (see links above), but in this case I was thinking of fields, rather than variables.
(有人指出存在类似的问题(请参阅上面的链接),但是在这种情况下,我在考虑字段而不是变量。)
The difference is that fields can be undefined
and there is no runtime error when using them.(区别在于字段可以是undefined
并且使用它们时没有运行时错误。)
I updated my question accordingly.(我相应地更新了我的问题。)
EDIT 2:
(编辑2:)
This question was closed because there are similar questions.
(因为存在类似的问题,所以已关闭此问题。)
I think there is a slight difference here, because in my question I'm checking a field/property of an object, not a variable.(我认为这里有细微的差别,因为在我的问题中,我要检查的是对象的字段/属性,而不是变量。)
For properties, it's more common to check for undefined
than for variables, where checking for undefined
is quite rare.(对于属性,检查undefined
比检查变量更常见,在这种情况下,检查undefined
非常罕见。)
Actually, it doesn't make sense to check variable === undefined
since it would throw an error when the variable is undefined.(实际上,检查variable === undefined
毫无意义,因为当变量未定义时会抛出错误。)
ask by Ferran Maylinch translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…