检查数组是否包含指定的对象

Check if an array contains a specified object

本文关键字:对象 包含指 数组 是否 检查      更新时间:2023-09-26

以下函数通过具有嵌套数组的对象递归搜索对象:

function findDeep(arr, obj) {
  console.log(arr)
  if (arr.indexOf(obj) !== -1) {
    console.log(arr)
    return arr
  } else {
    arr.forEach(item => {
      if (item.children) findDeep(item.children, obj)
    })
  }
}
const colors = {
  children: [
    {
      name: 'white',
    },
    {
      name: 'yellow',
      children: [
        {
          name: 'black'
        }
      ]
    }
  ]
}
const color = {
  name: 'black'
}
findDeep(colors.children, color)

第一个console.log(arr)记录匹配的阵列:

[
  { name: 'black' }
]

但第二个console.log(arr)没有记录任何内容。arr.indexOf(obj)不应该返回1,从而使第二个console.log(arr)记录数组吗?

这是CodePen。

使用indexOf在数组中找不到objectindex,除非两个对象(在indexOf中传递以进行测试并存在于数组中)都指向同一引用。

例如:

var a = {
  a: 10
};
var b = [{
  a: 10
}, {
  b: 20
}];
console.log(b.indexOf(a)); // Object `a` and Object in `0th` index of the array are having similar `key-values`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

但是,

var a = {
  a: 10
};
var b = [a, {
  b: 20
}];
//`0th` index in the array is nothing but a variable holding `object`
console.log(b.indexOf(a)); //Same variable is tested in `indexOf`
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

在文档中,indexOf()使用严格相等(与===或三重相等运算符使用的方法相同)将searchElement与Array的元素进行比较。

{} === {}将被评估为false,因为

只有当操作数引用同一Object时,比较Object的表达式才为true。如果两个操作数都是对象,则JavaScript比较当操作数引用内存中的同一对象时相等的内部引用。【参考】

目前的解决方案和方法很少,但都是在对象中对keyvalue进行迭代和比较。请参阅答案