如何将对象解构为已定义的变量? [英] How to destructure an object to an already defined variable?

查看:14
本文介绍了如何将对象解构为已定义的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下产生语法错误:

let source,
    screenings,
    size;

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

{
    screenings,
    size
} = source;

预期结果:

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

推荐答案

您需要使用 无声明赋值 语法:

({
    screenings,
    size
} = source);

Babel REPL 示例

来自链接的文档:

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

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

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

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;

这篇关于如何将对象解构为已定义的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆