更喜欢解构——已经存在的变量

Prefer destructuring - already exisiting variable

我的 linter 给我带来了关于解构的麻烦。


当我尝试解构时,它让我出错,如以下代码片段所示:

const data = {
  status: 'example',
};

let status = 'foo';

{
  status,
} = data;

console.log(status);

当变量已经存在时,有什么方法可以使用解构吗?


再次使用 let :

const data = {
  status: 'example',
};

let status = 'foo';

let {
  status,
} = data;

console.log(status);

在解构周围添加括号

来自文档:Assignment without declaration

The parentheses ( ... ) around the assignment statement are required 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}

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

const data = {
  status: 'example',
};

let status = 'foo';

({ status } = data);

console.log(status);