【问题标题】:Pure Functions In JavaScript ES6JavaScript ES6 中的纯函数
【发布时间】:2017-05-12 02:16:34
【问题描述】:

由于某些未知原因,我无法让对象传播在我的代码中工作。我不得不依靠'Object.assign()',但宁愿使用'...'

以下作品:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

// create new object and mutate that one
const selfEducate = person =>
  Object.assign({}, person,
    {canRead:true},
    {canWrite:true}
  );

console.log(selfEducate(frederick));  // { name: 'Frederick Douglass', canRead: true, canWrite: true }
console.log(frederick);  // { name: 'Frederick Douglass', canRead: false, canWrite: false }

但是,以下不是:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

const selfEducate = person =>
  ({
    ...person,
    canRead: true,
    canWrite: true
  });

console.log(selfEducate(frederick));
console.log(frederick);

那个错误是:

SyntaxError: Unexpected token ...

展开运算符在我的其他涉及复制数组的代码中确实有效,但在本示例中不适用。任何反馈将不胜感激。

【问题讨论】:

  • 在对象文字中,这是一个即将推出的功能(很可能),并且在大多数实现中不受支持。 kangax.github.io/compat-table/esnext/…
  • 您在哪个浏览器上尝试javascript 提问?
  • ES7 在这方面用词不当。 ES7 已经完结,ES8几乎完结了。像这样的对象传播仍然是一个提议,尽管它最终可能会出现在 ES9 中。
  • @loganfsmyth:这就是为什么我更喜欢使用 ES20XX 来指代最新版本(即 ES2016、ES2017)。

标签: javascript ecmascript-next


【解决方案1】:

如果您的其他代码部分正在使用扩展运算符对数组进行操作,这与尝试扩展对象字面量不同。

规范有提议,例如here

【讨论】:

    【解决方案2】:

    请尝试以下步骤。

    安装

    npm install --save-dev babel-plugin-transform-object-rest-spread

    在现有预设中的使用

    “插件”:[“transform-object-rest-spread”]

    参考链接:Click here

    注意:对象扩展运算符不是默认功能。它需要如上所述的转译器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-11
      • 2021-02-19
      • 2019-01-06
      • 2018-05-25
      • 2020-03-21
      • 1970-01-01
      • 2016-05-11
      • 2022-01-21
      相关资源
      最近更新 更多