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

为何JavaScript数组some()方法判断对象内数组时返回false?

问题原因及解决方案

为什么代码返回false?

你写的判断条件 menuItem.ingredients === 'flour' 是在把数组和字符串做严格相等比较。在JavaScript里,数组属于引用类型,字符串是基本类型,引用类型和基本类型用===比较永远返回false——哪怕数组里包含这个字符串,数组本身和字符串也不是同一个值。

举个直观的例子:

console.log(["flour"] === "flour"); // 输出 false

所以你的some()方法遍历每个菜品时,每个判断结果都是false,最终整体返回false。

正确的写法

要检查数组中是否包含某个元素,应该用数组的includes()方法:

const menu = [{
    name: "tofu fritters",
    ingredients: ["tofu", "egg yolk", "breadbrumbs", "paprika"],
  },
  {
    name: "black bean curry",
    ingredients: ["black beans", "garam masala", "rice"],
  },
  {
    name: "chocolate tiffin",
    ingredients: [
      "dark chocolate",
      "egg",
      "flour",
      "brown sugar",
      "vanilla essence",
    ],
  },
  {
    name: "hummus",
    ingredients: ["chickpeas", "tahini", "lemon", "garlic", "salt"],
  },
];

searchResult = menu.some(menuItem => menuItem.ingredients.includes('flour'));
console.log(searchResult); // 输出 true

includes()方法会遍历目标数组,判断是否存在指定元素,只要找到就返回true,这样some()只要碰到一个满足条件的菜品,就会立刻返回true。

你提到“移除对象内的数组时才返回true”,应该是指把ingredients直接改成字符串'flour',这时menuItem.ingredients === 'flour'变成字符串和字符串的比较,自然返回true,但这不符合你原本要检查数组包含元素的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:01:44