简体   繁体   English

如何在不使程序崩溃的情况下检查不存在的变量的值?

[英]How do I check the value of a non-existent variable without crashing the program?

I have a JSON output from an HTTP get.我从 HTTP 得到一个 JSON output。 I am then using JSON.parse from nodejs.然后我使用来自 nodejs 的 JSON.parse。

The output is basically like this: output 基本上是这样的:

items: [
    snippet: {
        foo: "bar",
        bar: "foo
    }
    snippet: {
        foo: "bar",
        bar: "foo
    }
    snippet: {
        foo: "bar",
        bar: "foo
    }
]

My code is then as such:我的代码是这样的:

foo1 = items[0].snippet.foo
bar1 = items[0].snippet.bar

this variable declaration all works fine, until I get to the variables that might not exist sometimes.这个变量声明一切正常,直到我得到有时可能不存在的变量。

foo4 = items[4].snippet.foo

Of course, this right here does not exist.当然,这里是不存在的。 I thought that I would be able to simply do an if(foo4 == 'Null') then set foo4 = 'not existing' so it does not crash my program later.我以为我可以简单地做一个 if(foo4 == 'Null') 然后设置 foo4 = 'not existing' 这样它以后就不会崩溃我的程序。 However, the program crashes when DECLARING this variable itself... how can I prevent this from happening?但是,当声明这个变量本身时程序崩溃了......我怎样才能防止这种情况发生?

in ES2020 there is cool feature called optional chaining and nullish coalescing , so you can try to combine them:在 ES2020 中有一个很酷的特性叫做optional chainingnullish coalescing ,所以你可以尝试将它们结合起来:

foo4 = items[4]?.snippet?.foo ?? 'not existing'

So if items[4] is null or undefined part items[4]?.snippet?.foo will set undefined to foo4 and then operator ??因此,如果items[4]是 null 或未定义的部分items[4]?.snippet?.foo会将 undefined 设置为 foo4 然后将 operator ?? will add default value to variable foo 4将默认值添加到变量 foo 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM