javascript中是否有类似于可选链接的东西

javascript中是否有类似于可选链接的东西,javascript,syntax,Javascript,Syntax,在访问数据时,可选链接功能非常强大,例如 const options = cache.[server]?.[channel]?.[service] 现在,在编写数据时,我们通常需要执行以下操作 cache[server] ??= {} cache[server][channel] ??= {} cache[server][channel][service] = options 有没有像可选链接这样的东西可以使这样的导航更轻(可能在一行中)?比如: cache[server]??{}:[ch

在访问数据时,可选链接功能非常强大,例如

const options = cache.[server]?.[channel]?.[service]
现在,在编写数据时,我们通常需要执行以下操作

cache[server] ??=  {}
cache[server][channel] ??= {}
cache[server][channel][service] = options
有没有像可选链接这样的东西可以使这样的导航更轻(可能在一行中)?比如:

cache[server]??{}:[channel]??{}:[service]=options
在这种情况下,在后面添加
{}
[]
将允许指示如果为null,预期分配的内容


按照@Bergi的建议,最接近的方法是这样写:

((cache[server] ??= {})[channel] ??= {})[service] = options

您可以减少第一个键的数组,并保留赋值的最后一个属性

[server, channel]
    .reduce((o, k) => o[k] ??= {}, cache)
    [service] = options;
或在一个方便的功能

const
    assign (object, [...keys], value) => {
        const last = keys.pop();
        keys.reduce((o, k) => o[k] ??= {}, object)[last] = value;
    }

// call
assign(cache, [server, channel, service], options);

可以使用括号来变换

cache[server] ??= {}
cache[server][channel] ??= {}
cache[server][channel][service] = options
变成一个单一的表达

((cache[server] ??= {})[channel] ??= {})[service] = options

在Coffeescript
cache[server]??{}:[channel]??{}:[service]=options
-这就是我所说的可读、干净的code@kinduser语法可以改进,但是它仍然比创建所有中间对象的一系列
if
语句要好。@Justinas它在Coffescript中是如何调用的?@RolandStarke你能给我举个例子吗?虽然它不是合成糖,但它是我要求的最模块化的方法,但是你的解决方案并不像我想象的那样模块化,我试图使你的解决方案更合适,但最后它使事情变得太复杂了