简体   繁体   中英

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

I have a JSON output from an HTTP get. I am then using JSON.parse from nodejs.

The output is basically like this:

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. 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:

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 ?? will add default value to variable foo 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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