为什么ECMASCRIPT 6在解构时会反转各方的分配? [英] Why did ECMASCRIPT 6 reverse the sides for assignment when destructuring?

查看:101
本文介绍了为什么ECMASCRIPT 6在解构时会反转各方的分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么ES6决定左侧任务更有意义,或者对于结构化任务更有用?刚开始看,它似乎使代码更容易出错,现在根据情况可以在双方进行分配。

Why did ES6 decide that left-side assignment made more sense or was more useful for destructured assignments? Just on first look, it seems to make code more error prone, now that assignment can happen on both sides, depending on situation.

let obj = { first: 'Jane', last: 'Doe' };
let { first: f, last: l } = obj;
// f = 'Jane'
// l = 'Doe'

f和l似乎都在左边定义,使用左边的var名称和右边的vars值的组合值。

f and l are both seemingly being defined on the left, using values from a combination of the var names on the left and values of those vars from the right.

给定这个sytax的基本原理是保持它与对象声明语法相同,为什么ECMA不会使用:

Given that the rationale for this sytax is the keep it the same as object declaration syntax, why would ECMA not instead have used:

let { f: first, l: last } = obj;


推荐答案

因为它应该保留对象文字语法:属性名称位于冒号之前。语法应该嵌套,如果目标位于左侧,则无法正常工作:

Because it is supposed to keep the object literal syntax: the property name comes before the colon. The syntax is supposed to nest, and that wouldn't work properly if the target was on the left side:

let {propName: [arrayElement, ...moreElements], otherName: {nestedProp: targetName}} = obj;

在您的方法中,它将是

let {[arrayElement, ...moreElements]: propName, {targetName = nestedProp}: otherName} = obj;

冒号没有任何意义。

这篇关于为什么ECMASCRIPT 6在解构时会反转各方的分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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