问题
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 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.
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;
回答1:
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;
In your approach, it would be
let {[arrayElement, ...moreElements]: propName, {targetName = nestedProp}: otherName} = obj;
where the colon doesn't make any sense.
来源:https://stackoverflow.com/questions/40698433/why-did-ecmascript-6-reverse-the-sides-for-assignment-when-destructuring