我可以预先声明变量以解析对象的分配吗? [英] Can I pre-declare variables for destructuring assignment of objects?

查看:49
本文介绍了我可以预先声明变量以解析对象的分配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

当我尝试使用数组解构赋值时,我能够预先声明我的变量:

When I tried destructuring assignment with arrays I was able to pre-declare my variables:

let a, b, c;
let arr = [1, 2, 3, 4, 5];
[a, b, c] = arr;

console.log(a) // logs 1
console.log(b) // logs 2
console.log(c) // logs 3

这很好地通过了Babel编译器。

This went through the Babel compiler just fine.

但是当我试图用对象做同样的错误时我得到了一个错误

However when I tried to do the same with objects I got an error

let a, b, c
let obj = {cat: 'meow', dog: 'woof', mouse: 'squeak'};
{cat: a, dog: b, mouse: c} = obj;

console.log(a) // I want this to log 'meow'
console.log(b) // I want this to log 'woof'
console.log(c) // I want this to log 'squeak'

问题

这是ES6还是Babel怪癖/问题?如果它是ES6的故意,为什么与数组的处理方式有所不同?

Is this an ES6 or Babel quirk/problem? If it's intentional for ES6, why the difference from the way arrays are treated?

注意

我理解用替换 var 意味着我不需要预先声明我的变量和拥有内联是有效的(而且,我相信,通常是首选)。我想知道实现之间的区别而不是不要那样做答案。

I understand that replacing var with let means I'm not required to pre-declare my variables and that having the let inline is valid (and, I believe, generally prefered). I'd like to know about the difference between implementations rather than a "don't do it like that at all" answer.

推荐答案

当您破坏对象时,


  1. 您需要使用与对象中的键相同的变量名称。只有这样你才会得到一对一的对应关系,价值将被正确解构。

  1. you need to use the same variable names as the keys in the object. Only then you will get one to one correspondence and the values will be destructured properly.

如果你不使用,你需要将整个作业包装在括号中声明语句,否则左侧表达式中的对象文字将被视为一个块,您将获得SyntaxError。

and you need to wrap the entire assignment in parenthesis if you are not using declaration statement, otherwise the object literal in the left hand side expression would be considered as a block and you will get SyntaxError.



< hr>

所以你的固定代码就像这样


So your fixed code would be like this

'use strict';
let cat, dog, mouse;
let obj = {cat: 'meow', dog: 'woof', mouse: 'squeak'};
({cat, dog, mouse} = obj);     // Note the `()` around

你实际上可以写为

'use strict';
let obj = {cat: 'meow', dog: 'woof', mouse: 'squeak'};
let {cat, dog, mouse} = obj;

这篇关于我可以预先声明变量以解析对象的分配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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