indexOf method in an object array?

前端 未结 27 2950
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
27条回答
  •  天涯浪人
    2020-11-22 02:51

    If your object is the same object of the ones you are using within the array, you should be able to get the index of the Object in the same way you do as if it was a string.

    var hello = {
        hello: 'world',
        foo: 'bar'
    };
    var qaz = {
        hello: 'stevie',
        foo: 'baz'
    }
    
    var qazCLONE = { // new object instance and same structure
        hello: 'stevie',
        foo: 'baz'
    }
    
    var myArray = [hello,qaz];
    
    myArray.indexOf(qaz) // should return 1
    myArray.indexOf(qazCLONE) // should return -1
    

提交回复
热议问题