【问题标题】:Javascript (ES6) const with curly braces [duplicate]带有花括号的Javascript(ES6)常量[重复]
【发布时间】:2016-02-21 06:57:45
【问题描述】:

我是 ECMAScript 6 的新手,在尝试学习 Ember 时,我偶尔会看到以下代码样式:

const {
  abc,
  def
} = Object;

我搜索了 Google 和许多解释新 ES6 规范的网站。我知道这不是当前的实现,因为我的控制台在输入时会出错。

这段代码是什么意思?

更新

我将这个 sn-p 粘贴到 Babel's transpiler,这是它返回的内容:

"use strict";

var abc = Object.abc;
var def = Object.def;

我仍然对这试图完成什么感到困惑。

【问题讨论】:

  • 这是一个例子,当想要玩一些 ES6 的东西时,这是一个不错的网站。 es6fiddle.net/ih5zgb2r
  • 呃。 const {someKey} = someObj 如何更好地替代 const someKey = someObj.someKey
  • @ZachSmith,当您有多个时,这是一个不错的选择,例如下面接受的答案中的const {name, version, type} = app; 示例。
  • @jaywalker - 是的。我现在几乎经常使用它
  • 人员 = { 年龄:45,性别:f,薪水:2000 ... } const {薪水,年龄,性别} = 人员与 const 薪水 = 人员工资 const 性别 = 人员性别常量年龄 = 人员年龄

标签: javascript ecmascript-6 constants


【解决方案1】:

这是一个destructuring assignment。具体来说,object destructuring 分配。

以更详细的方式重写它可能会有所帮助。

const abc = Object.abc;
const def = Object.def;

这是一种从对象属性初始化变量的简写方式。

const name = app.name;
const version = app.version;
const type = app.type;

// Can be rewritten as:
const { name, version, type } = app;

您也可以对数组做同样的事情。

const a = items[0];
const b = items[1];
const c = items[2];

// Can be written as:
const [a, b, c] = items;

【讨论】:

猜你喜欢
  • 2019-02-25
  • 2014-11-26
  • 2017-07-21
  • 2016-12-08
  • 2020-09-28
  • 2018-04-25
  • 1970-01-01
  • 2012-01-10
  • 2017-05-22
相关资源
最近更新 更多