用于一系列空/未定义检查的Javascript最佳实践



给定以下路径,如果可能,我想返回"name",否则返回":

countries[0].states[0].cities[0].name

一种选择是逐步检查:

if(countries && countries[0]){
    var states = countries[0].states;
    if(states && states[0]){
        var cities = states[0].cities;
        if(cities && cities[0]){
            var name = cities[0].name;
            if(name){
               return name;
            }
        }
    }
}
return "";

这太冗长了。另一种选择是异常处理:

try {
   var name = countries[0].states[0].cities[0].name;
   return name ? name : ""; // handle null or undefined
} catch(err) {
   return "";
}

但是,在普通逻辑上涉及异常处理可能会让我们感到不舒服,而且这也会降低性能。

还有其他简单/干净的方法吗?

您可以构建一个助手来完成它:

function readProperties(object, path) {
    return path.reduce(function (object, key) {
        return object && object[key];
    }, object);
}
…
return readProperties(countries, [0, 'states', 0, 'cities', 0, 'name']) || '';

如果使用lodash.js或下划线,可以执行以下操作:

    if (_.get(countries, '[0].states[0].cities[0].name')) {
    }   

最新更新