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
How to destructure an object to an already defined variable?
提问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);
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 let
variable. If you were using var
, you could just redeclare var { screenings, size } = source;
显然你需要使用它,因为你不能重新声明一个let
变量。如果您正在使用var
,则可以重新声明var { screenings, size } = source;