How to avoid 'cannot read property of undefined' errors?

前端 未结 16 2206
野性不改
野性不改 2020-11-22 06:02

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:



        
16条回答
  •  一向
    一向 (楼主)
    2020-11-22 06:21

    Update:

    • If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
    • TypeScript has added support for optional chaining in version 3.7.
    // use it like this
    obj?.a?.lot?.of?.properties
    

    Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:

    A quick workaround is using a try/catch helper function with ES6 arrow function:

    function getSafe(fn, defaultVal) {
        try {
            return fn();
        } catch (e) {
            return defaultVal;
        }
    }
    
    // use it like this
    getSafe(() => obj.a.lot.of.properties);
    
    // or add an optional default value
    getSafe(() => obj.a.lot.of.properties, 'nothing');
    

    Working snippet:

    function getSafe(fn, defaultVal) {
      try {
        return fn();
      } catch (e) {
        return defaultVal;
      }
    }
    
    // use it like this
    console.log(getSafe(() => obj.a.lot.of.properties));
    
    // or add an optional default value
    console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));

    See this article for details.

提交回复
热议问题