简体   繁体   English

如何处理JavaScript条件语句中的可为空的对象

[英]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.

相关问题 如何在条件语句中使用 javascript new Date() 对象? - How do I use javascript new Date() objects in conditional statements? 我应该如何处理嵌套条件语句? - How should I deal with nested conditional statements? Javascript引擎如何处理条件语句和循环中的代码? - How does Javascript engine deal with code inside conditional statements and loops? 如果我的应用中有其他条件语句,我该如何重构这些javascript? - How do I refactor these javascript if else conditional statements in my app? 如何使条件语句中的条件语句起作用? - How do I make conditional statements within conditional statements work? 如何对对象使用条件语句 - How to use conditional statements on objects 如何获得第一个对象的颜色属性? 我们基本上如何处理 JavaScript 或 Typescript 中的对象数组 - How do I get the first object's property which is color? How do we basically deal with an array of objects in JavaScript or Typescript 我如何在不使用对象和switch语句的情况下使这种javascript语言更加雄辩? - How do I make this javascript more eloquent without using objects and switch statements? IE条件语句不能在禁用JavaScript的情况下使用? - IE conditional statements do not work with JavaScript disabled? 如何处理带有条件字段的 javascript 表单中的安全性 - How to deal with security in a javascript form with conditional fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM