【问题标题】:Why {source:target} when destructing in Javascript? [duplicate]为什么在 Javascript 中解构时使用 {source:target}? [复制]
【发布时间】:2019-02-09 21:54:44
【问题描述】:

为什么在 Javascript 中破坏新变量时是 const {source:target} = obj 而不是相反?

我问的是因为const {target:soruce} = obj 会更符合...

const source = 'x';
const obj = {target:source};

...而且我会少犯错误。 :)

【问题讨论】:

  • targetsource 以这种方式解构的属性的 别名
  • 我明白了。如果是const {source as target} = obj 就像import {source as target} from 'lib' 我不会有任何问题。
  • 必须询问建立语法的委员会。虽然有明确的记录
  • 考虑到: target 位是可选的,const {source: target} = obj 更有意义。只需const {source} = obj 行创建一个等于obj["source"]source 变量。 const {source:target} 为您提供了一个选项来创建与您定位的键不同的变量名称。
  • 在处理嵌套解构时使用as 或反向操作也会变得难看

标签: javascript


【解决方案1】:

你的问题很有趣。所以,我想对此发表我的看法:

const { 源:目标 } = 对象

1) 两边应该相等:

x = x

2) 所以,两者都是对象:

{ source } = object

3) 如果对象以某种方式未定义怎么办?

{ source } = object || { source: 'the value - not an alias' }

4) 提取的是键,而不是值

const { source } // and source will hold the value

5) 如果使用 as 会怎样?

const { source as target } = object
// like we have
// export { source as target } from 'module'

嵌套对象键会非常困难:

const obj = { source: { target: 'another value' } }
const { source: { target: asValue } } = obj

如果我们使用 as,你能想一想吗?

const { source of target as asValue } // makes life no easier.

但是使用导入/导出语法只有一个考虑因素。

import { a, b, c } from 'module'

但不是:

import { a, b, c } from 'module', 'another-module', 'third-module'

希望,现在说得通了!

如果您实际上在使用解构语法时遇到了困难,那么您可以查看并点击我的another post 中提供的链接。

【讨论】:

    【解决方案2】:

    如果您将其格式化为:

     ({ source: target  } =
      { source: "value" });
    

    尤其是嵌套属性:

    ({ source1: { source2: target  }} =
     { source1: { source2: "value" }});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-28
      • 2016-05-19
      • 2019-03-11
      • 2017-03-11
      • 2021-07-22
      • 2016-07-06
      • 1970-01-01
      • 2010-12-28
      相关资源
      最近更新 更多