背景
当我尝试用数组解构分配时,我可以预先声明变量:
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编译器就可以了。
但是,当我尝试对对象执行相同操作时,出现错误
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,为什么要区别对待数组的方式呢?
笔记
据我所知,更换var
与let
我不需要预先声明我的变量手段和具有let
内联是有效的(而且,我相信,一般者优先)。我想知道实现之间的区别,而不是“根本不那样做”的答案。
当您分解对象时,
您需要使用与对象中的键相同的变量名。只有这样,您才能获得一对一的对应关系,并且值将正确解构。
并且如果不使用声明语句,则需要将整个赋值都用括号括起来,否则左侧表达式中的对象文字将被视为一个块,并且会出现语法错误。
所以你的固定代码看起来像这样
'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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句