尝试在javascript中捕获未定义的检查

时间:2018-01-04 08:06:39

标签: javascript

我有一个方法findResult

function findResult(response){
 if (response[0].firstProperty.Value > 0)
     return true;
 else false;
}

在此方法中,如果响应对象未定义,则会出现javascript错误。我的问题是是否使用显式未定义检查或将代码包装在try / catch周围,如下所示:

function findResult(response){
 try{
    if (response[0].firstProperty.Value > 0)
     return true;
    else return false;
 }
 catch(e){
   return false;
 }

}

2 个答案:

答案 0 :(得分:0)

您可以通过简单的检查来避免尝试捕获

if (response && response.length && response[0].firstProperty.Value > 0) { ... }

如果您有权访问lodash:

if (_.get(response, '[0].firstProperty.Value', 0) > 0) { ... }

答案 1 :(得分:0)

Javascript没有此功能原生。

但是网上有一些这样的实现。例如:

function deepGet (obj, props, defaultValue) {
    // If we have reached an undefined/null property
    // then stop executing and return the default value.
    // If no default was provided it will be undefined.
    if (obj === undefined || obj === null) {
        return defaultValue;
    }

    // If the path array has no more elements, we've reached
    // the intended property and return its value
    if (props.length === 0) {
        return obj;
    }

    // Prepare our found property and path array for recursion
    var foundSoFar = obj[props[0]];
    var remainingProps = props.slice(1);

    return deepGet(foundSoFar, remainingProps, defaultValue);
}

用法:

var rels = {
    Viola: {
        Orsino: {
            Olivia: {
                Cesario: null
            }
        }
    }
};
var oliviaRel = deepGet(rels, ["Viola", "Orsino", "Olivia"], {});

来源:http://adripofjavascript.com/blog/drips/making-deep-property-access-safe-in-javascript.html