Javascript:使用`.includes`查找对象数组是否包含特定对象 [英] Javascript: Using `.includes` to find if an array of objects contains a specific object
本文介绍了Javascript:使用`.includes`查找对象数组是否包含特定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对javascript ES6有点陌生,并且我很难理解为什么以下内容无法按预期运行:
I am a bit new to javascript ES6, and I am having difficulty understanding why the below is not functioning as expected:
let check = [{name: 'trent'},{name: 'jason'}].includes({name: 'trent'});
// expect true - returns false
谢谢!
推荐答案
includes
本质上检查是否有元素===
您要搜索的元素.对于对象,===
的含义实际上是相同的对象,与相同的引用(在内存中的相同位置)相同,而不是相同的形状.
includes
essentially checks if any element ===
the element you're searching for. In case of objects, ===
means literally the same object, as in the same reference (same place in memory), not the same shape.
var a1 = { name: 'a' }
var a2 = { name: 'a' }
console.log(a1 === a2) // false because they are not the same object in memory even if they have the same data
但是,如果您搜索实际上在数组中的对象,那么它将起作用:
But if you search for an object that is actually in the array it works:
var a1 = { name: 'a' }
var a2 = { name: 'a' }
var array = [a1, a2]
console.log(array.includes(a1)) // true because the object pointed to by a1 is included in this array
这篇关于Javascript:使用`.includes`查找对象数组是否包含特定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文