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
相关产品推荐
相关产品推荐

