array indexOf with objects?

前端 未结 3 1586
情书的邮戳
情书的邮戳 2020-12-21 18:10

I know we can match array values with indexOf in JavaScript. If it matches it wont return -1.

var test = [
    1, 2, 3
]

// Returns 2
test.indexOf(3);
         


        
3条回答
  •  余生分开走
    2020-12-21 18:55

    This is kind of custom indexOf function. The code just iterates through the items in the object's array and finds the name property of each and then tests for the name you're looking for. Testing for 'Josh' returns 0 and testing for 'Kate' returns 1. Testing for 'Jim' returns -1.

    var test = [
      {
        name: 'Josh'
      },
      {
        name: 'Kate'
      }
    ]
    
    myIndexOf('Kate')
    
    function myIndexOf(name) {
      testName = name;
      for (var i = 0; i < test.length; i++) {
        if(test[i].hasOwnProperty('name')) {
          if(test[i].name === testName) {
            console.log('name: ' + test[i].name + ' index: ' + i);
            return i;
          }
        }
      }
      return -1;
    }
    

提交回复
热议问题