Home  >  Q&A  >  body text

javascript - Does Jquery's inArray method not support judging objects?

It works when the array element is a number or a string, but not when it is an object

漂亮男人漂亮男人2711 days ago901

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:25:32

    Objects in js are reference type values, and the comparison of two objects is the comparison of the referenced memory addresses. Like the following code:

    var obj1={};
    var obj2={};
    obj1===obj2     //false
    

    Although these two objects appear to be equal, they refer to different objects in the heap memory, so they are not equal.

    The implementation of

    inArray should be to traverse the array, compare each item of the array with the target value, and return the index value if they are equal, and -1 if they are not equal. Due to the above reasons, the reference values ​​​​of the two separately declared objects are not the same. are equal, so -1 is returned.

    reply
    0
  • 阿神

    阿神2017-05-19 10:25:32

    It is generally understood that an array is an object, but the object is not necessarily an array. inArray works on arrays

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:25:32

    In the source code, isArray: Array.isArray is used. It can also contain objects inside, but the outer layer must be [].

    var obj = [{a:1}];
    console.log(Array.isArray(obj))  // true

    reply
    0
  • Cancelreply