深度解读js中数组的findIndex方法

js中数组有一个findIndex方法,这个方法是一个让人感到很困惑的方法。

首先来看看MDN对这个方法的解释:Array.prototype.findIndex() - JavaScript | MDN

The findIndex() method of Array instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

See also the find() method, which returns the first element that satisfies the testing function (rather than its index).

 上面这段话简单说就是:findIndex函数会遍历数组所有元素,返回满足给定测试函数的数组元素的索引,如果所有数组元素都不满足条件,则返回-1。

这个描述还是有点拗口,我们看看findIndex的入参

array.findIndex( callback(element) )

 这里采用的是简化版本,因为99%都是这种情况,没有必要把问题搞复杂。

可以看到findIndex接收的是一个回调函数,而回调函数的入参就是数组中的每一个元素

findIndex 方法会从数组的第一个元素开始迭代,对每个元素调用 callback 函数,直到找到一个使 callback 返回 true 的元素。一旦找到这样的元素,findIndex 将返回该元素的索引,如果没有找到满足条件的元素,则返回 -1。

 下面举个简单的例子:

const numbers = [1, 2, 3, 4, 5];
// findIndex中回调函数就是判断数组中元素是否大于3,满足条件则返回该元素的索引值
const index = numbers.findIndex(element => element > 3);

console.log(index); // 输出:3,因为数字 4 是第一个满足条件的元素,其索引为 3

这个例子很容易看懂,就不多做解释了。

然后再举一个复杂些的例子:

function deleteFromArray(arr, compare) {
  // 注意:这里的compare就是findIndex的callback回调函数,该回调函数在实际调用的时候才确定传入
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}
export function deleteSearch(query) {
  let searches = storage.get(SEARCH_KEY, [])
  // (item) => {return item === query}就是实际传入的回调函数,item是数组searches中的每一个元素
  deleteFromArray(searches, (item) => {
// 判断条件: 如果找到search中跟查询关键词query相同的元素,就返回它的索引;否则返回-1
    return item === query 
  })
  storage.set(SEARCH_KEY, searches)
  return searches
}

上面这个例子中是把findIndex的callback回调函数当作参数传递给了deleteFromArray函数,这样就保证了灵活性。

deleteFromArray通过这个回调函数的判断结果,拿到索引,然后通过splice方法从数组中删除这个元素

在某种意义上,findIndex跟filter函数有点像,但还是有区别,主要为:

findIndex 用于找到第一个满足条件的元素并返回其索引

filter 用于获取所有满足条件的元素组成的新数组

 简单说findIndex 返回的是符合条件数组元素的索引,而filter返回的是符合条件的数组元素的一个集合=》一个新数组。

你可能感兴趣的:(javascript,findIndex)