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

JavaScript中两种箭头函数写法差异及筛选失效问题解析

问题:两段箭头函数筛选逻辑为何结果不同?

需求目标

从JSON文件中筛选出包含指定所有配料(并非仅包含这些配料)的鸡尾酒。

单个鸡尾酒JSON结构

总数据量400+,单个对象结构如下:

{
    "strGlass": "White Wine Glass",
    "idDrink": "15346",
    "strCreativeCommonsConfirmed": "No",
    "strCategory": "Cocktail",
    "strInstructionsIT": "Miscela con ghiaccio.\r\nServire in un bicchiere da vino.\r\nGuarnire con una carota.",
    "strInstructions": "Blend with ice. Serve in a wine glass. Garnish with carrot.",
    "strDrink": "155 Belmont",
    "Ingredients": [
      {
        "Measurement": "1 shot ",
        "Ingredient": "Dark rum"
      },
      {
        "Ingredient": "Light rum",
        "Measurement": "2 shots "
      },
      {
        "Measurement": "1 shot ",
        "Ingredient": "Vodka"
      },
      {
        "Measurement": "1 shot ",
        "Ingredient": "Orange juice"
      }
    ],
    "dateModified": "2016-10-05 12:36:28",
    "strDrinkThumb": "https://www.thecocktaildb.com/images/media/drink/yqvvqs1475667388.jpg",
    "strAlcoholic": "Alcoholic",
    "strInstructionsDE": "Mit Eis vermischen. In einem Weinglas servieren. Mit Karotte garnieren."
}

使用的变量定义

let Filterable_Drinks = reactive([]);
let Ingredients_Searched_For = reactive(["vodka", "lemonade"]);

第一种写法(正常返回结果)

Filterable_Drinks.length = 0;

const items = DRINKS.filter(cocktail => Ingredients_Searched_For.every(ing => cocktail.Ingredients.find(cocIng => cocIng.Ingredient.toLowerCase().includes(ing.toLowerCase()))))

Filterable_Drinks.push(...items);
console.log(Filterable_Drinks);

第二种写法(返回空数组)

Filterable_Drinks.length = 0;

const items = DRINKS.filter((cocktail) => {
    Ingredients_Searched_For.every((ing) => {
      cocktail.Ingredients.find(cocIng => cocIng.Ingredient.toLowerCase().includes(ing.toLowerCase()))
    })
  })

Filterable_Drinks.push(...items);
console.log(Filterable_Drinks);

差异原因

核心问题在于箭头函数的返回值规则:

  • 第一种写法用了无大括号的箭头函数:cocktail => ...,这种写法会隐式返回箭头右侧表达式的结果,也就是Ingredients_Searched_For.every(...)的布尔值,filter会根据这个布尔值判断是否保留当前鸡尾酒对象。
  • 第二种写法给filter的回调加了大括号{},此时箭头函数不会自动返回值,必须显式写return。当前代码里没有return语句,所以回调默认返回undefined,而undefined属于假值,filter会把所有元素都过滤掉,最终得到空数组。

修正第二种写法只需要加上return:

const items = DRINKS.filter((cocktail) => {
    // 加上return,返回every的判断结果
    return Ingredients_Searched_For.every((ing) => {
      return cocktail.Ingredients.find(cocIng => cocIng.Ingredient.toLowerCase().includes(ing.toLowerCase()))
    })
  })

内容的提问来源于stack exchange,提问作者ssethzz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:54:24