使用可选链接分配变量? [英] Assigning a variable using optional chaining?

查看:49
本文介绍了使用可选链接分配变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在撰写本文时,我知道只有少数浏览器支持它,但是是否有一种聪明的方法可以通过可选的链接为深层嵌套对象中的键分配一个值呢?我尝试了以下类似操作,但对我而言无效:

I know that only a few browsers support it as of this writing, but is there a clever way to assign a value to a key in a deeply nested object via optional chaining? I tried something like below, but it didn't work for me:

const foo = {bar: {baz: {quux: ''}}};
foo?.bar?.baz?.quux = 'quux'  // Uncaught SyntaxError: Invalid left-hand side in assignment

我唯一想到的方法是通过以下方式对其进行条件检查:

The only way I could think of would just be to do a conditional check for it via:

if (foo?.bar?.baz?.quux)
  foo.bar.baz.quux = 'quux'

也许有更好的方法吗?

推荐答案

某些代码(例如Google中的某些代码)将执行以下操作:

Some code such as some code in Google would do something like:

const foo = {bar: {baz: {quux: ''}}};

foo && foo.bar && foo.bar.baz && (foo.bar.baz.quux = 'quux');
console.log(foo);

console.log(foo && foo.bar && foo.bar.wahla && foo.bar.wahla.haha);

但是,如果 foo.bar 是真实值而不是对象,则会有问题.

but it'd be problematic if foo.bar is a truthy value and not an object.

这篇关于使用可选链接分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆