JavaScript箭头函数`elements.map(({ length }) => length)`语法解析求助
Great question! That last arrow function uses object destructuring in function parameters—a super handy syntax that lets you extract properties directly from the argument being passed in, skipping the need for a placeholder variable like element. Let’s break it down step by step:
1. Context: What map is doing
First, remember that Array.map() iterates over each element in the array and passes that element to the callback function. In your example, each element is a string (like 'Hydrogen'), which in JavaScript acts like an object with a length property.
2. The destructured parameter ({ length })
The ({ length }) in the arrow function’s parameter list is shorthand for:
// Equivalent longhand logic const element = /* current string from the array */; const { length } = element; // Extracts element.length into a variable named length
By putting the destructuring directly in the parameter, we’re telling JavaScript: "Take the argument passed to this function (each string), grab its length property, and make that property available as a variable named length inside the function."
3. The arrow function body => length
Since the function only needs to return the length variable we just extracted, we can use the implicit return syntax of arrow functions—no need for curly braces or a return keyword.
Comparing to the longer versions
Let’s line it up with the more verbose examples to see the equivalence:
- Original function:
elements.map(function(element) { return element.length; }); - Basic arrow function:
elements.map(element => { return element.length; }); - Destructured arrow function:
elements.map(({ length }) => length);
All three do exactly the same thing—they return an array of each string’s length. The last one just cuts out the middleman (the element variable) by extracting the property we care about right in the parameter.
Quick note on the difference from object literal returns
You mentioned knowing about ({}) in the arrow function body (like () => ({ key: value }) to return an object literal). That’s a different use case: there, the parentheses are to avoid confusing the JavaScript parser between function body curly braces and object literal braces. The destructuring in the parameter list uses curly braces to extract properties from the input argument—two separate but related syntax features!
内容的提问来源于stack exchange,提问作者Kurt Peek

