Difference Between indexOf and findIndex function of array

后端 未结 7 596
暗喜
暗喜 2020-11-30 19:42

I am confused between the difference between the two function indexOf and find Index in an array.

The documentation says

findIndex - Returns

7条回答
  •  青春惊慌失措
    2020-11-30 20:29

    FindIndex is useful if you want to find the first element that matches to your predicate: In W3C's example, there are numbers and matches if the customer's age above or equals to 18.

    var ages = [3, 10, 18, 20];
    
    function checkAdult(age) {
        return age >= 18;
    }
    
    console.log(ages.findIndex(checkAdult));
    

    console:

    2
    

    You can find an exact element index with the indexOf function of Array, but you can't pass a predicate. It is faster if you want to find a specific element:

    var ages = [3, 10, 18, 20];
    console.log(ages.indexOf(10));
    

    returns:

    1
    

    Index counting starts at 0, so the first element index is 0.

提交回复
热议问题