求教:两个JavaScript箭头函数为何等价?新手解析语法疑问
Hey there! Let's break this down nice and simple since you're getting started with JavaScript arrow functions. First, let's make sure we're on the same page with the two examples you're looking at:
The first function (you already get this one):
// Takes an object `d`, returns its `length` property const getLength = d => d.length;
The second function (the confusing one):
// Uses object destructuring in the parameter list const getLength = ({ length }) => length;
Let's unpack the { length } syntax first
That curly brace syntax in the parameter is called object destructuring—it's a handy JavaScript shortcut that lets you pull specific properties directly from an object when it's passed as an argument.
Here's what's happening under the hood with the second function:
- When you pass an object (like
{ length: 10, otherProp: "hi" }) to the function, the{ length }in the parameter list is essentially saying: "Take thelengthproperty from the incoming object, and create a variable namedlengththat holds that value." - It's the exact same as writing this longer, more explicit version:
const getLength = d => { const length = d.length; return length; };
Why they're completely equivalent
Both functions do the exact same core task, just with different syntax:
- They accept an object as input
- They access the
lengthproperty of that object - They return that
lengthvalue
The only difference is that the second function uses destructuring to skip the step of manually assigning d.length to a variable—it handles that assignment directly in the parameter list.
Think of it like this: instead of grabbing the whole box (the object d) and then reaching inside to pull out the length item, destructuring lets you just ask for the length item right when you're handed the box.
内容的提问来源于stack exchange,提问作者geekydude703

