谁能向我解释为什么以下两个箭头函数是等价的?

can anyone explain to me why the following two arrow functions are equivalent?

我是 javascript 的新手。在 MDN 上看到了关于箭头函数的内容。

任何人都可以向我解释第二个是如何工作的吗?我理解第一个。 不太清楚为什么我们把长度放在对象中,然后 return 长度???

案例1(我从ES5转换过来的理解):

materials.map((material) => {
return material.length;
}); // [8, 6, 7, 9]

案例 2(不明白 {length} 在这里做什么以及为什么我们 return length:

materials.map(({length}) => length); // [8, 6, 7, 9]

非常感谢!

更新:

所以从 Jeff B 的回答来看。似乎第二个正在用解构做以下事情:

materials.map(({length}) => length)

其中 {length} 将设置变量 var length 等于 materials.length;这就是为什么我们可以简单地 return length。这就说得通了。谢谢杰夫

这使用了 destructuring assignment to get at the length property without saving the whole object. Specifically, this is a case of "object destructuring".

例如:

let yourObject = {foo: 1, bar: 2}
let {bar} = yourObject;
// bar now equals 2

考虑到这一点,您可以看到 ({length}) => length 如何将名称 length 设置为第一个参数 length 属性 然后 然后立即 returns it——使两个表达式等价。