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

JS技术问题:如何查找owners数组包含Sarah的数组对象?

解决方法

你的问题出在判断逻辑上:acc.owners是一个数组,而你用===直接和字符串'Sarah'做比较,数组和字符串属于不同类型,永远不可能相等,所以find方法找不到匹配的对象。

正确的做法是用数组的includes()方法,检查acc.owners数组里是否包含'Sarah':

const findeOwner = dogs.find(acc => acc.owners.includes('Sarah'));

举个完整示例,假设你的dogs数组结构如下:

const dogs = [
  { name: '旺财', owners: ['张三', '李四'] },
  { name: '来福', owners: ['Sarah', 'Tom'] },
  { name: '小白', owners: ['王五'] }
];

运行正确代码后,findeOwner会得到{ name: '来福', owners: ['Sarah', 'Tom'] }这个匹配对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:25:13