javascript 如何将对象解构为已定义的变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32138513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:54:34  来源:igfitidea点击:

How to destructure an object to an already defined variable?

javascriptecmascript-6

提问by Gajus

The following produces a syntax error:

以下会产生语法错误:

let source,
    screenings,
    size;

source = {
    screenings: 'a',
    size: 'b'
};

{
    screenings,
    size
} = source;

Expected result:

预期结果:

screenings should be equal to 'a'
size should be equal to 'b'

回答by CodingIntrigue

You need to use assignment without declarationsyntax:

您需要使用没有声明语法的赋值

({
    screenings,
    size
} = source);

Babel REPL Example

Babel REPL 示例

From the linked docs:

从链接的文档:

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

在没有声明的情况下使用对象字面量解构赋值时,赋值语句周围的 ( .. ) 是必需的语法

And obviously you need to use this as you can't redeclare a letvariable. If you were using var, you could just redeclare var { screenings, size } = source;

显然你需要使用它,因为你不能重新声明一个let变量。如果您正在使用var,则可以重新声明var { screenings, size } = source;