2

当父属性不存在时,让 js 返回 undefined 而不是抛出错误的最佳方法是什么?

例子

a = {}
b = a.x.y.z
// Error: Cannot read property 'value' of undefined
// Target result: b = undefined
4

4 回答 4

3

您必须检查每个属性是否存在:

var b;
if (a.x && a.x.y && a.x.y.z) {
    b = a.x.y.z
}

或者,类似于另一张海报的“safeGet”功能:

var get = function (obj, ns) {
    var y = ns.split('.');
    for(var i = 0; i < y.length; i += 1) {
        if (obj[y[i]]) {
            obj = obj[y[i]];
        } else {
            return;
        }
    }
    return obj;
};

利用:

var b = get(a, 'x.y.z');
于 2012-06-07T17:14:23.657 回答
2

我会稍微冗长:

var b = ((a.x || {}).y || {}).z
于 2012-06-07T17:11:10.113 回答
2
try {
  a = {}
  b = a.x.y.z
}
catch (e) {
  b = void 0;
}
于 2012-06-07T17:07:57.270 回答
1

您可以编写一个safeGet辅助函数,例如:

按照 arcyqwerty 评论中的建议进行了深入编辑

var getter = function (collection, key) {
    if (collection.hasOwnProperty(key)) {
        return collection[key];
    } else {
        return undefined;
    }
};

var drillDown = function (keys, currentIndex, collection) {
    var max = keys.length - 1;
    var key = keys[currentIndex];

    if (typeof collection === 'undefined') {
        return undefined;   
    }

    if (currentIndex === max) {
        return getter(collection, key);
    } else {
        return drillDown(keys, currentIndex + 1,
                         getter(collection, key));
    }
};

var safeGet = function (collection, key) {
    if (key.indexOf(".") !== -1) {
        return drillDown(key.split("."), 0, collection);
    } else {
        return getter(collection, key);
    }
};

a = { x: 1 };
b = safeGet(a, 'x.y.z');

http://jsfiddle.net/YqdWH/2/

于 2012-06-07T17:17:49.867 回答