gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:03:41 26 4
gpt4 key购买 nike

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

enter image description here


当我试图解构时,它让我出错,就像下面的片段:

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);

关于javascript - 更喜欢解构——已经存在的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56866132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com