Node.JS中的解构

时间:2013-06-29 10:34:20

标签: javascript node.js ecmascript-6 destructuring

This recent video声称EMCAScript 6解构已部分在Node.JS中实现。我尝试了各种示例(使用v0.10.12和--harmony标志),例如

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

var {a: a, b: b} = {a: 1, b: 2};

无济于事。 This ticket似乎表明V8尚未支持解构。

在Node.JS中,解构是否真的部分实现了?什么是我可以使用的代码片段?

3 个答案:

答案 0 :(得分:88)

节点v6及更新版本的更新:节点v6支持解构分配,无需任何特殊需要:

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

对于旧版本的节点:您可以通过输入以下内容获取支持的和声功能列表:

node --v8-options | grep harmony

节点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已添加到节点4.1中。目前,您需要传递--harmony_destructuring标志才能启用该功能:

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

答案 1 :(得分:14)

最近发布的 node.js v6 正在使用V8版本5.0,这是ESQ15语言功能的supporting 93%(在v6.1中甚至是96%)。

现在可以认为解构分配是稳定的,可以在没有任何标记的情况下使用。

答案 2 :(得分:10)

ES6 compatibility table表明Chrome 45或Node v4不支持解构。

相关问题