一系列null / undefined检查的Javascript最佳实践

时间:2015-07-04 18:03:51

标签: 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 "";
}

但我们可能会对简单逻辑涉及异常处理感到不舒服,而costs performance也是如此。

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

2 个答案:

答案 0 :(得分:2)

您可以构建一个帮助程序来执行此操作:

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

答案 1 :(得分:1)

如果你使用lodash.js或下划线,你可以这样做:

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

    }