Javascript 奇怪的对象数组和 indexOf [英] Javascript oddness with array of objects and indexOf

查看:33
本文介绍了Javascript 奇怪的对象数组和 indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不太明白这里发生了什么.给定数组 (arr):

<预><代码>[{"first_name": "丹","last_name": "伍德森",身份证":1},{"first_name": "珍","last_name": "伍德森",身份证":2},{"first_name": "耀西","last_name": "伍德森",身份证":3}]

和对象(obj):

<代码>{"first_name": "耀西","last_name": "伍德森",身份证":3}

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

解决方案

Array.indexOf() 仅当提供的对象与您放入的对象完全相同.

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

arr[i] === obj

您需要展示您如何检索该对象.

Not quite grasping what's going on here. Given the array (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
    }
]

And the object (obj):

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

Why would arr.indexOf(obj) return -1 (especially since I retrieved the object from the array using it's 'id' parameter earlier in the function)?

解决方案

Array.indexOf() will only work on objects if the supplied object is exactly the same object you put in.

An exact copy is insufficient, it has to be the exact same object, i.e. there must be some object in the array such that:

arr[i] === obj

You need to show how you retrieved the object.

这篇关于Javascript 奇怪的对象数组和 indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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