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

前端 未结 16 2505
野性不改
野性不改 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

    I like Cao Shouguang's answer, but I am not fond of passing a function as parameter into the getSafe function each time I do the call. I have modified the getSafe function to accept simple parameters and pure ES5.

    /**
    * Safely get object properties.    
    * @param {*} prop The property of the object to retrieve
    * @param {*} defaultVal The value returned if the property value does not exist
    * @returns If property of object exists it is returned, 
    *          else the default value is returned.
    * @example
    * var myObj = {a : {b : 'c'} };
    * var value;
    * 
    * value = getSafe(myObj.a.b,'No Value'); //returns c 
    * value = getSafe(myObj.a.x,'No Value'); //returns 'No Value'
    * 
    * if (getSafe(myObj.a.x, false)){ 
    *   console.log('Found')
    * } else {
    *  console.log('Not Found') 
    * }; //logs 'Not Found'
    * 
    * if(value = getSafe(myObj.a.b, false)){
    *  console.log('New Value is', value); //logs 'New Value is c'
    * }
    */
    function getSafe(prop, defaultVal) {
      return function(fn, defaultVal) {
        try {
          if (fn() === undefined) {
            return defaultVal;
          } else {
            return fn();
          }
        } catch (e) {
          return defaultVal;
        }
      }(function() {return prop}, defaultVal);
    }
    

提交回复
热议问题