javascript 忽略-if-null 运算符?

标签 javascript operator-overloading null-conditional-operator

<分区>

在 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'));

但这不是很可读。

最佳答案

正确的捷径可能是

if (((ctrl || {}).main || {}).user) { // ...

或者您可以使用数组作为路径,或使用点分隔的字符串作为路径并检查是否存在并返回值。

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"));

关于javascript 忽略-if-null 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022410/

相关文章:

javascript - 使用 javascript 切换表单可见性

C# 如何创建泛型类?

c++ - 运算符作为函数指针

c# - 类型转换调用链中的 Elvis 运算符

javascript - 使用 Javascript 从父窗口访问子窗口元素

javascript - jQuery 延迟和 promise 无法正常工作

Javascript 移动检测

c++ - 在 C++ 中重载 ">>"和 "<<"

c# - LINQ:搜索对象列表的多个字段,其中字段可以为空

c# - 当 text 为 null 时,text?.IndexOf(ch) != -1 为 True?