Node.JS 中的解构赋值

77

这个最近的视频声称,EMCAScript 6 解构已经在 Node.JS 中部分实现。我尝试了各种不同的例子(使用 v0.10.12 和 --harmony 标志),例如:

var [a, b] = [1, 2];

并且。
var {a: a, b: b} = {a: 1, b: 2};

无济于事。 这个问题 似乎表明在V8中还不支持解构。

Node.JS是否真的部分实现了解构?我可以尝试哪些代码片段?

3个回答

91

Node v6及更高版本的更新:Node v6支持解构赋值,无需进行任何特殊设置:

var [a, b] = [1, 2];

对于旧版本的Node:您可以通过输入以下命令获取支持的ES6语法特性列表:

node --v8-options | grep harmony

Node 5.x将会返回以下结果:

--es_staging (enable all completed harmony features)
--harmony (enable all completed harmony features)
--harmony_shipping (enable all shipped harmony fetaures)
--harmony_modules (enable "harmony modules" (in progress))
--harmony_regexps (enable "harmony regular expression extensions" (in progress))
--harmony_proxies (enable "harmony proxies" (in progress))
--harmony_sloppy_function (enable "harmony sloppy function block scoping" (in progress))
--harmony_sloppy_let (enable "harmony let in sloppy mode" (in progress))
--harmony_unicode_regexps (enable "harmony unicode regexps" (in progress))
--harmony_reflect (enable "harmony Reflect API" (in progress))
--harmony_destructuring (enable "harmony destructuring" (in progress))
--harmony_default_parameters (enable "harmony default parameters" (in progress))
--harmony_sharedarraybuffer (enable "harmony sharedarraybuffer" (in progress))
--harmony_atomics (enable "harmony atomics" (in progress))
--harmony_simd (enable "harmony simd" (in progress))
--harmony_array_includes (enable "harmony Array.prototype.includes")
--harmony_tostring (enable "harmony toString")
--harmony_concat_spreadable (enable "harmony isConcatSpreadable")
--harmony_rest_parameters (enable "harmony rest parameters")
--harmony_sloppy (enable "harmony features in sloppy mode")
--harmony_arrow_functions (enable "harmony arrow functions")
--harmony_new_target (enable "harmony new.target")
--harmony_object_observe (enable "harmony Object.observe")
--harmony_spreadcalls (enable "harmony spread-calls")
--harmony_spread_arrays (enable "harmony spread in array literals")
--harmony_object (enable "harmony Object methods")

你需要的标志是 --harmony_destructuring,它是在 Node 4.1 中添加的。目前,您需要传递 --harmony_destructuring 标志以启用该功能:

$ node --harmony_destructuring
> var {foo} = {foo: 'bar'};
undefined
> foo
'bar'

3
没有使用 var,你需要执行 ({foo} = {foo: 'bar}),以防止前导的 { 被解释为开始一个代码块。这在任何实现中都是一样的。 - user663031
有趣,我没有想到过。虽然在解构数组时应该能够省略 var/let,但在 Node 中似乎还不能实现。 - Brian McCutchon

15

最近发布的node.js v6使用的是V8 5.0版本,该版本支持93%的ES2015语言特性(在v6.1中甚至达到了96%)。

解构赋值现在可以被认为是稳定的,并且可以在没有任何标志的情况下使用。


10

1
即使使用 node --harmony_destructuring - Ahmed Fasih
7
在 Node v5.0.0 版本中,它可以通过运行 node --harmony_destructuring 命令来启用解构赋值。我不清楚 v4 版本是否也支持。 - kernel
6
在Node 4.2.2版本中,使用--harmony_destructuring 对我有效。 - Oleksii Rudenko
截至最新的Chrome(49),解构现在得到支持。只要你坚持使用Chrome或Node(带有适当的标志),你现在可以使用几乎所有ES6,甚至不需要像Babel这样的转译器。 - machineghost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接