JavaScript中带{}的箭头函数执行机制——数组find函数异常解析
Great question! Let's break down exactly what's happening here with JavaScript arrow functions and the Array.find() method.
First, let's revisit your test code for clarity:
// 数组声明 const phones = [{ brand: "Samsung", id: 10 }, { brand: "Apple", id: 20 }]; // 正确写法 let phone = phones.find(phone => phone.id === 10); console.log("Correct result: ", phone); // 错误写法 phone = phones.find(phone => { phone.id === 10; }); console.log("Wrong result: ", phone);
What's the key difference between the two arrow functions?
Arrow functions have two core syntax variations, and this is where your issue originates:
Implicit return (no curly braces): When you write an arrow function without curly braces (
phone => phone.id === 10), JavaScript automatically treats the single expression after the arrow as the function's return value. So this callback returns the boolean result ofphone.id === 10(truewhen the id matches 10,falseotherwise). Thefind()method uses this boolean to locate the first matching element, which gives you the correct result.Explicit function body (with curly braces): Adding curly braces means you're defining a full function body. In this scenario, JavaScript does not automatically return any value unless you explicitly use the
returnkeyword. Your incorrect callback{ phone.id === 10; }runs the comparison expression but doesn't return it—so the function defaults to returningundefined.
Why does this break find()?
The Array.find() method requires its callback to return a truthy value for the element you want to retrieve. Since undefined is falsy, find() treats every element as a non-match. After checking all elements without getting a truthy return value, it returns undefined—which is your "wrong result".
Fixing the incorrect version
To make the curly brace version work as expected, just add the return keyword to explicitly return the comparison result:
phone = phones.find(phone => { return phone.id === 10; });
This matches the behavior of the implicit return version, giving you the correct matching element.
内容的提问来源于stack exchange,提问作者user11661871

