二者都是查找数组中满足条件的第一个元素的索引。
indexOf
indexOf() 方法返回在数组中可以找到的一个给定元素的第一个索引,如果不存在,则返回-1。
const num = [1,2,3,4,5];
console.log(num.indexOf(6));//-1
findIndex
findIndex()方法返回数组中满足提供测试函数的第一个元素的索引。若没有找到返回-1.
const num = [1,2,3,4,5];
const hasLarge = (ele) => ele > 3;
console.log(num.findIndex(hasLarge));//3
区别
- indexOf:查找值作为第一个参数,多用于查找基本类型,若果对象类型,则是判断是否是同一个对象的引用。
- findIndex:比较函数作为第一个参数,多用于非基本类型的数组索引查找,或查找条件很复杂。