简体   繁体   中英

How do I solve the “cannot read property … of undefined” with out using try/catch?

This function is designed to count all items in array of a specific type. However, when there are zero elements of a certain type I receive the "cannot read property ... of undefined" error. I have tried to fix it using the typeof keyword, but it hasn't worked. Is my syntax correct and how would I fix this issue?

function typeCount(type){
    if (typeof (base.getbyType(type)) === "undefined"){ return 0;  }
    else { return base.getbyType(type).length;}
}
var pCount = typeCount('pen');

Simply have getbyType return an empty array on no matches - then no check is needed:

function typeCount(type){
    return base.getbyType(type).length;
}

However, if the posted codes throws the exception then the error is elsewhere - as in, not inherently with the .length access. Consider these possible causes:

  • base itself evaluates to undefined. The correct fix for this is to make sure base cannot be undefined. A guard here just hides the problem and should likely not be used!

  • The exception is thrown from within getbyType . This means the function is broken - fix it.

  • getbyType is not consistent and returns undefined only-sometimes. This means the function is broken - fix it.

And, if the getbyType insists on not returning an empty array for no matches, use a temporary variable. This also avoids the unnecessary duplicate work that is done by the original code.

function typeCount(type){
    var res = base.getbyType(type);
    return (typeof res === "undefined") ? 0 : res.length;
}

Or, not caring if it is strictly undefined (what good is null.length ?) ..

function typeCount(type){
    var res = base.getbyType(type);
    return res ? res.length : 0;
}

Or, if we're feeling "clever" (note that getbyType is still only called once)..

function typeCount(type){
    return (base.getbyType(type) || []).length;
}

You can try this way:

function typeCount(type){
    if (base.getbyType(type) === undefined){ return 0;  }//modified code here
    else { return base.getbyType(type).length;}
}
var pCount = typeCount('pen');

you can try this

function typeCount(type){
    if (base && base.getbyType && typeof (base.getbyType(type)) === "undefined"){ return 0;  }
    else { return base.getbyType(type).length;}
}
var pCount = typeCount('pen');

maybe base or base.getbyType undefined

function typeCount(type){
    if (typeof base === 'undefined' || !base.getbyType || base.getbyType(type) === "undefined"){ return 0;  }else { return base.getbyType(type).length;}
}
var pCount = typeCount('pen');

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