Destructure and assign to new variable at the same time not working

故事扮演 提交于 2019-12-12 03:14:48

问题


I am trying to destructure object and assign it to new variable at the same time:

let {x} = a = {x: 'cool'};
console.log(a, x);

which outputs:

//Object { x: "cool" } cool - in Firefox
//ReferenceError: a is not defined - in Chrome, babel-node

Why is there difference and what is the correct behavior?

UPDATE:

This is maybe more generic use case. While this works in all environments:

var a = b = {x: 'cool'};

this statement is not working in chrome/babel-node:

var {x} = a = {x: 'cool'}; //SyntaxError: Unexpected token {

There is also different error message when using var instead of let.


回答1:


In your code, a is not defined. let a = b = c does not define b. You need to say

let a = {x: 1}, {x} = a;

Firefox doesn't support let, so I'm wondering how your example worked there at all. See https://kangax.github.io/compat-table/es6/.



来源:https://stackoverflow.com/questions/34856507/destructure-and-assign-to-new-variable-at-the-same-time-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!