Node.js 8.9.4 中使用默认参数的对象解构

Object destructuring with default parameters in Node.js 8.9.4

我在将这段代码保存到文本文件时遇到了问题 运行 并且 运行 在命令行中使用了节点。

let x;

{k1: x = null } = {k1: "Hello"};
console.log(x);

运行 这会在赋值运算符无效时引发错误。

然而,当代码直接输入节点解释器时,它会打印出 "Hello",这正是我所期望的。

有人知道这是什么吗?这个想法是用默认值构造一个 class 并使用相同的方法更新 class ,在缺少某些内容时重用当前值。

你必须使用assignment wihout declaration

let x;
({k1: x = null } = {k1: "Hello"});

或者只是:

let { k1: x = null } = { k1: "Hello" };

The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.