【问题标题】:Javascript oddness with array of objects and indexOf对象数组和 indexOf 的 Javascript 奇怪之处
【发布时间】:2011-12-23 16:13:31
【问题描述】:

不太了解这里发生了什么。给定数组(arr):

[
    {
        "first_name": "Dan",
        "last_name": "Woodson",
        "id": 1
    },
    {
        "first_name": "Jen",
        "last_name": "Woodson",
        "id": 2
    },
    {
        "first_name": "Yoshi",
        "last_name": "Woodson",
        "id": 3
    }
]

还有对象(obj):

{
    "first_name": "Yoshi",
    "last_name": "Woodson",
    "id": 3
}

为什么arr.indexOf(obj) 会返回-1(尤其是因为我在函数前面使用它的“id”参数从数组中检索了对象)?

【问题讨论】:

  • “函数的早期”是什么意思?您需要向我们展示您编写的失败的代码,而不仅仅是一些 JSON。
  • 你能发布你正在使用的实际代码,和/或把它放在 fsFiddle 上吗?
  • 这是因为({a:12}) === ({a:12})false。如果 JavaScript 中的对象是相同的对象(相同的引用),则它们是相等的,而不仅仅是相同的值。

标签: javascript arrays object indexof


【解决方案1】:

Array.indexOf() 仅适用于提供的对象与您放入的对象完全相同的对象。

精确的副本是不够的,它必须是完全相同的对象,即数组中必须有一些对象:

arr[i] === obj

您需要展示您是如何检索对象的。

【讨论】:

    【解决方案2】:

    我想查看检索功能,但很可能您没有使用相同的引用。因为以下是正确的:

    var a = {id: 3};
    var b = [a];
    b.indexOf(a); // 0
    a.id = "not three";
    b.indexOf(a); // still 0
    

    但是,以下内容会中断:

    var a = {id: 3};
    var b = [{id: 3}];
    b.indexOf(a); // -1 not the same object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2015-04-22
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2011-10-24
      相关资源
      最近更新 更多