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

查看:225
本文介绍了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天全站免登陆