在javascript中我有很多像这样的代码。
if (ctrl && ctrl.main && ctrl.main.user) {
SetTheme(ctrl.main.user.theme);
}
这很烦人。在其他语言中,您只需
SetTheme(ctrl?.main?.user?.theme);
有没有办法在javascript中这样做?
我试过了,
function safeGet(a,b) { return a ? a[b] : null; }
和
SetTheme(safeGet(safeGet(safeGet(ctrl, 'main'), 'user'), 'theme'));
但那不是很可读。
答案 0 :(得分:1)
您可以创建一个通用函数,方法是将表示路径的字符串传递给您想要的嵌套属性:
function getValue(object, prop, /*optional*/ valIfUndefined) {
var propsArray = prop.split(".");
while(propsArray.length > 0) {
var currentProp = propsArray.shift();
if (object.hasOwnProperty(currentProp)) {
object = object[currentProp];
} else {
if (valIfUndefined) {
return valIfUndefined;
} else {
return undefined;
}
}
}
return object;
}
然后在任何对象上使用它,如:
// This will return null if any object in the path doesn't exist
if (getValue(ctrl, 'main.user', null)) {
// do something
}
答案 1 :(得分:1)
正确的捷径可能是
if (((ctrl || {}).main || {}).user) { // ...
或者您可以使用数组作为路径,或者使用点分隔的字符串作为路径并检查aginst是否存在并返回值。
function getValue(object, path) {
return path.split('.').reduce(function (o, k) {
return (o || {})[k];
}, object);
}
var ctrl = { main: { user: { theme: 42 } } };
console.log(getValue(ctrl, "main.user.theme"));