当父属性不存在时,让 js 返回 undefined 而不是抛出错误的最佳方法是什么?
例子
a = {}
b = a.x.y.z
// Error: Cannot read property 'value' of undefined
// Target result: b = undefined
当父属性不存在时,让 js 返回 undefined 而不是抛出错误的最佳方法是什么?
例子
a = {}
b = a.x.y.z
// Error: Cannot read property 'value' of undefined
// Target result: b = undefined
您必须检查每个属性是否存在:
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');
我会稍微冗长:
var b = ((a.x || {}).y || {}).z
try {
a = {}
b = a.x.y.z
}
catch (e) {
b = void 0;
}
您可以编写一个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');