indexOf method in an object array?

前端 未结 27 2917
别跟我提以往
别跟我提以往 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:36

    You can use a native and convenient function Array.prototype.findIndex() basically:

    The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.

    Just a note it is not supported on Internet Explorer, Opera and Safari, but you can use a Polyfill provided in the link below.

    More information:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

    var hello = {
      hello: 'world',
      foo: 'bar'
    };
    var qaz = {
      hello: 'stevie',
      foo: 'baz'
    }
    
    var myArray = [];
    myArray.push(hello, qaz);
    
    var index = myArray.findIndex(function(element, index, array) {
      if (element.hello === 'stevie') {
        return true;
      }
    });
    alert('stevie is at index: ' + index);

提交回复
热议问题