节点v6在对象传播上失败 [英] Node v6 failing on object spread

查看:93
本文介绍了节点v6在对象传播上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,为什么节点v6.7无法运行此代码:

I had a question about why node v6.7 would be failing to run this code:

var a = {
    foo: 'bar'
}

var b = {
    ...a,
    my: 'sharona'
}
console.log(b)

任何人都知道为什么会这样吗?我以为v6支持对象传播..?但是我想不是吗?这是我看到的错误:

Anyone have an idea why that would be? I thought v6 supported object spreading..? But I guess not? Here is the error I'm seeing:

/home/teselagen/ve/tnrtest.js:6
    ...a,
    ^^^
SyntaxError: Unexpected token ...
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

推荐答案

看起来像ES6传播算子仅适用于数组和可迭代对象.它专门针对对象不工作而设计:

Looks like ES6 spread operator only works for arrays and iterables. It is specifically designed to NOT WORK for objects: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator

相关报价:

仅申请可迭代项

Only apply for iterables

var obj = {"key1":"value1"};
function myFunction(x) {
    console.log(x); // undefined
}
myFunction(...obj);
var args = [...obj];
console.log(args, args.length) //[] 0

尽管MDN文章先前曾建议,尝试在对象上使用散布运算符应导致未定义,而不是引发错误.从此修订开始,当前的MDN文章讨论了对为对象文字扩展"的支持

Though the MDN article previously suggested that trying to use the spread operator on objects should result in undefined instead of throwing an error. As of this revision, the current MDN article discusses support for "Spread for object literals"

另外,node.js兼容性表声称node.js完全符合使用数组和可迭代对象的散布运算符的规范,但特别指出不支持对象的rest/spread属性:如其他答案所示)

Additionally the node.js compatibility table claims node.js fully comply with the specification of the spread operator with arrays and iterables, but specifically indicates that object rest/spread properties are not supported: http://node.green/#ESNEXT-candidate--stage-3--object-rest-spread-properties, at least not until Node version 8.60 (at which point the color turns green to indicate that beginning in 8.3, Node does support the object spread/rest operator, as pointed out in the other answer)

这篇关于节点v6在对象传播上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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