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

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

    You can avoid getting an error by giving a default value before getting the property

    var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
    
    for (i=0; i<test.length; i++) {
        const obj = test[i]
        // No error, just undefined, which is ok
        console.log(((obj.a || {}).b || {}).c);
    }

    This works great with arrays too:

    const entries = [{id: 1, name: 'Scarllet'}]
    // Giving a default name when is empty
    const name = (entries.find(v => v.id === 100) || []).name || 'no-name'
    console.log(name)

    0 讨论(0)
  • 2020-11-22 06:30

    I usually use like this:

     var x = object.any ? object.any.a : 'def';
    
    0 讨论(0)
  • 2020-11-22 06:38

    I use undefsafe religiously. It tests each level down into your object until it either gets the value you asked for, or it returns "undefined". But never errors.

    0 讨论(0)
  • 2020-11-22 06:41

    In str's answer, value 'undefined' will be returned instead of the set default value if the property is undefined. This sometimes can cause bugs. The following will make sure the defaultVal will always be returned when either the property or the object is undefined.

    const temp = {};
    console.log(getSafe(()=>temp.prop, '0'));
    
    function getSafe(fn, defaultVal) {
        try {
            if (fn() === undefined) {
                return defaultVal
            } else {
                return fn();
            }
    
        } catch (e) {
            return defaultVal;
        }
    }
    
    0 讨论(0)
提交回复
热议问题