[英]How do I deal with nullable objects in JavaScript conditional statements
I have a variable that can either be set to false
or to an object xyz
. 我有一个可以设置为
false
或对象xyz
的变量。
I want to do something like this: 我想做这样的事情:
if (var1) {
if (var1.x.y.z === 1) {
// do stuff
}
} else {
// do something if var1 OR var1.x.y.z === 1 is false
}
I'm having trouble setting up this conditional statement without having to duplicate the else code for the outer if statement and the inner if statement. 我在设置此条件语句时遇到麻烦,而不必为外部if语句和内部if语句重复else代码。
Try using !!, this evaluates whatever the variable is as truthy or falsy. 尝试使用!!,这将评估变量为真还是假。 Basically if var1 is not not false, thus true.
基本上,如果var1不为false,则为true。 If var1 is anything but literally false then "do stuff".
如果var1除了字面上的错误,什么都不是,则“执行任务”。
Edited.. you can add the second test inline. 编辑..您可以添加第二个测试内联。
if (!!var1 && var1.x.y.z === 1) {
// do stuff
} else {
// do other stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.