JavaScript中的try catch用于undefined检查

3
我有一个名为 findResult 的方法。
function findResult(response){
 if (response[0].firstProperty.Value > 0)
     return true;
 else false;
}

在这种方法中,如果响应对象未定义,我们会得到一个javascript错误。我的问题是是否要使用显式的undefined检查或将代码包装在try / catch中,如下所示:
function findResult(response){
 try{
    if (response[0].firstProperty.Value > 0)
     return true;
    else return false;
 }
 catch(e){
   return false;
 }

}

https://dev59.com/1HI-5IYBdhLWcg3wKVE9 - atilkan
有很多种方法可以处理这个问题,没有一种方法比其他方法具有特别重的影响。(iftry()catch(){}无关紧要)https://dev59.com/m8-40IgBFxS5KdRjC-Wi真正的问题在于,如果“response”为“null”,您是否希望继续在同一块中执行代码。如果答案是否定的,则选择哪种解决方案并不重要。 - Timothy Groote
谢谢Timothy。使用显式检查,条件检查会变得太长。例如:if (response && response.length && response[0].firstProperty.Value > 0) - Sandeep Nagaraj
所以我正在检查什么是最佳方法。感谢您的回复。 - Sandeep Nagaraj
2个回答

0

你可以通过简单的检查避免使用 try catch

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

如果您可以访问lodash:
if (_.get(response, '[0].firstProperty.Value', 0) > 0) { ... }

0

Javascript本身不具备此功能。

但是在Web上有一些实现。例如:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接