Is it possible to check for null inline in javascript?

前端 未结 7 2288
孤街浪徒
孤街浪徒 2020-12-15 18:27

I have a function which parses the address components of the Google Maps API JSON and then returns the city / locality / route name.

The getAddre

7条回答
  •  無奈伤痛
    2020-12-15 19:17

    2020 Answer, It Exists!!!

    You can now directly use ?. inline to test for existence. It is called the Optional Chaining Operator, supported by all modern browsers.

    If a property exists, it proceeds to the next check, or returns the value. Any failure will immediately short-circuit and return undefined.

    const example = {a: ["first", {b:3}, false]}
    
    example?.a  // ["first", {b:3}, false]
    example?.b  // undefined
    
    example?.a?.[0]     // "first"
    example?.a?.[1]?.a  // undefined
    example?.a?.[1]?.b  // 3
    
    domElement?.parentElement?.children?.[3]?.nextElementSibling
    

    To ensure a default defined value, you can use ??. If you require the first truthy value, you can use ||.

    example?.c ?? "c"  // "c"
    example?.c || "c"  // "c"
    
    example?.a?.[2] ?? 2  // false
    example?.a?.[2] || 2  // 2
    

    If you do not check a case, the left-side property must exist. If not, it will throw an exception.

    example?.First         // undefined
    example?.First.Second  // Uncaught TypeError: Cannot read property 'Second' of undefined
    

    ?. Browser Support - 84%, Dec 2020

    ?? Browser Support - 84%

    Node Support - v14+

提交回复
热议问题