【问题标题】:JS how to use object destructuring after definition [duplicate]JS如何在定义后使用对象解构[重复]
【发布时间】:2018-12-21 08:39:42
【问题描述】:

抱歉,我知道这确实是一个愚蠢的问题,但经过几轮谷歌搜索后我找不到答案。代码如下:

let x = 0
// After some calculation I know the obj should be:
const obj = {'x': 1 }
// Then how to destructuring assigment at this line
{ x } = obj // this is incorrect
// But if I use: x = obj.x, ESLint warns me: [eslint] Use object destructuring. (prefer-destructuring)

console.log(x);

所以我的问题是如何在定义x 之后使用解构赋值。

【问题讨论】:

  • 我没有发现问题,const obj = {'x': 1}; const { x } = obj; 工作正常。你能显示更多代码吗?
  • @SamHolmes 谢谢!我从你的链接中得到了答案!
  • @dhilt 我在解构赋值之前定义了let x = 0。这与您的示例代码不同,您的是在定义时对 x 进行解构分配。谢谢大家!

标签: javascript destructuring


【解决方案1】:

初始化和销毁​​应该在同一行进行。如果你想设置一个初始值,为什么不使用default value赋值。

let { x = 0 } = obj

【讨论】:

  • 我的问题是在定义x 时我不知道obj 是什么。谢谢。
  • @LiuWenbin_NO.你没有在你的问题陈述中提到这一点。鉴于您当前的问题,这是一个完全有效的答案。
  • @PatrickRoberts OK.. 但我想我已经说过'// 经过一些计算我知道 obj 应该是:'
猜你喜欢
  • 2018-06-30
  • 2016-09-15
  • 2021-12-21
  • 1970-01-01
  • 2021-02-11
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
相关资源
最近更新 更多