节点5.10传播操作符不工作 [英] Node 5.10 spread operator not working

查看:96
本文介绍了节点5.10传播操作符不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,最新的节点(Node 5+)应该默认支持扩展运算符,如下所示:

According to the docs, the latest node (Node 5+) should support the spread operator by default, like so:

const newObj = {
        ...oldObj,
        newProperty: 1
      }

我已经安装了节点5.10.1(例如,这是节点-v'告诉我的)。但是我仍然收到这个错误:

And I have node 5.10.1 installed (e.g. that's what 'node -v' tells me). But I am still getting this error:

c:\[myprojectfolder]>node index.js
c:\[myprojectfolder]\index.js:21
            ...oldObj,
            ^^^

SyntaxError: Unexpected token ...
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:146:18)
    at node.js:404:3

我缺少什么?

推荐答案

数组支持语法,但对象扩展语法不是 - 这很可能由于它没有被定稿为ECMAScript规范的一部分(原来是原始的正式计划包括在ES7 / ES2016中,但如果我记得正确,它会被击倒。)

The array spread syntax is supported, but the object spread syntax is not - this is most likely due to it not being finalized as part of the ECMAScript spec yet (it was originally planned for inclusion in ES7/ES2016, but it got bumped back, if I recall correctly).

您的选项是使用透明机(如 Babel ,与 transform-object-rest-spread plugin),或者如果感觉像是过分的,可以使用新的内置 Object.assign 函数。对象传播语法实际上只是Object.assign周围的语法糖 - 您的问题中的示例可以这样表示:

Your options in the meantime are either to use a transpiler (such as Babel, with the transform-object-rest-spread plugin), or if that feels like overkill, you can use the new built-in Object.assign function. The object spread syntax is effectively just syntax sugar around Object.assign - the example in your question could be expressed like so:

const newObj = Object.assign({}, oldObj, {
    newProperty: 1
});

注意空对象作为第一个参数;来自其余传递对象的属性将合并到其中,最优先在函数调用优先级最远的对象。简单来说,只需将 oldObj 作为第一个参数看起来更直观,但这并不完全相同 - 它会使现有的 oldObj 以及返回。以空对象作为目标离开 oldObj 不变。

Note the empty object as the first argument; the properties from the rest of the passed objects get merged into it, with those furthest to the right of the function call taking priority. It may seem more intuitive to simply have oldObj as the first argument, but this doesn't have quite the same effect - it would mutate the existing oldObj as well as returning it. Having an empty object as the target leaves oldObj unchanged.

这篇关于节点5.10传播操作符不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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