Javascript oddness with array of objects and indexOf

后端 未结 2 1793
北荒
北荒 2020-11-29 12:26

Not quite grasping what\'s going on here. Given the array (arr):

[
    {
        \"first_name\": \"Dan\",
        \"last_name\": \"Woodson\",
        \"id\         


        
相关标签:
2条回答
  • 2020-11-29 12:57

    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.

    0 讨论(0)
  • 2020-11-29 13:14

    I would like to see the retrieve function, but most likely you are not using the same reference. Because the following is true:

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

    However, the following will break:

    var a = {id: 3};
    var b = [{id: 3}];
    b.indexOf(a); // -1 not the same object
    
    0 讨论(0)
提交回复
热议问题