You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求教:两个JavaScript箭头函数为何等价?新手解析语法疑问

Understanding the Equivalent Arrow Functions with Object Destructuring

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 the length property from the incoming object, and create a variable named length that 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:

  1. They accept an object as input
  2. They access the length property of that object
  3. They return that length value

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:22:26