Nodejs 还不支持从 Object 中 用 ... 解构 ?

Nodejs 还不支持从 Object 中 用 … 解构 ?
为啥数组就可以, 比如说


let [x, …y] = [‘a’, ‘b’, ‘c’];
// => x = ‘a’
// => y = [‘b’, ‘c’]
// OK 啊~
let {foo, …oths} = {foo: ‘bar’, x: 1, y: 2, z: 3}
// SyntaxError: Unexpected token …


参数也是可以的

const fn = (x, …oths) => {console.log(oths);}

为啥 Object 不可以 7.0 下能用吗?


9 回复

为什么我从手机 chrome 打开这页面是暗色 css ??


节点主题

因为现在 ecma rest operator 不支持 object
object 的 rest operator 是 stage 3 的规范
https://github.com/sebmarkbage/ecmascript-rest-spread

早就支持了, node 6.9 可用

object rest operator 还没支持,得配 babel + preset-stage3 , 或者转 object rest operator 的插件+stage2




thx~
而且现在只支持最后一个参数解构 比如
[a, b, …others] = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] // 这样是可以的
[a, …others, lastArg] = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] // 这样就不行

Nicholas Zakas 大神的书中有写:

Rest items must be the last entry in the destructured array and cannot be followed by a
comma. Including a comma after rest items is a syntax error.

所以你最后的 destructure 用的不对。
难道 ES2016 支持这种写法?

在 Node.js 中,使用展开运算符(...)来解构对象是完全支持的,这一特性是基于 ECMAScript 2018(ES9)标准引入的。展开运算符允许你将一个对象的所有可枚举属性,拷贝到当前对象字面量中。以下是一个简单的示例,展示了如何在 Node.js 中使用展开运算符解构对象:

// 定义一个对象
const obj = {
    a: 1,
    b: 2,
    c: 3
};

// 使用展开运算符解构对象
const { a, ...rest } = obj;

console.log(a); // 输出: 1
console.log(rest); // 输出: { b: 2, c: 3 }

// 另一个示例,将对象属性合并到新对象中
const newObj = {
    d: 4,
    ...rest
};

console.log(newObj); // 输出: { d: 4, b: 2, c: 3 }

上述代码展示了如何在 Node.js 环境中使用展开运算符来解构对象。如果你在使用 Node.js 时遇到无法使用展开运算符的情况,请检查以下几点:

  1. 确保你的 Node.js 版本至少是 8.3.0 或更高,因为这是支持对象展开运算符的最低版本。
  2. 检查你的代码是否有语法错误,例如对象字面量或解构赋值语句的格式是否正确。

如果问题依旧存在,请提供具体的错误信息或代码示例,以便进一步分析和解决。

回到顶部