Array.includes() 在数组中查找对象 [英] Array.includes() to find object in array

查看:326
本文介绍了Array.includes() 在数组中查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Array.prototype.includes 在数组中查找对象.这可能吗?我意识到浅比较和深比较是有区别的.这是下面代码返回false的原因吗?我找不到 Array.includes() 的相关答案.

I'm attempting to find an object in an array using Array.prototype.includes. Is this possible? I realize there is a difference between shallow and deep comparison. Is that the reason the below code returns false? I could not find a relevant answer for Array.includes().

推荐答案

Array.includes 通过对象标识进行比较,就像 obj === obj2 一样,所以遗憾的是这并没有除非这两个项目是对同一个对象的引用,否则不起作用.您通常可以使用 Array.prototype.some() 取而代之的是一个函数:

Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:

const arr = [{a: 'b'}]
console.log(arr.some(item => item.a === 'b'))

当然,您需要编写一个小函数来定义相等的含义.

But of course you then need to write a small function that defines what you mean by equality.

这篇关于Array.includes() 在数组中查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆