Web编程技术营地
研究、演示、创新

findIndex

撰写时间:2024-03-15

最新修订:2024-03-15

findIndex

返回数组中满足回调函数所设定的条件的第一个元素所在的索引值。

原型

numberfindIndex
  • functioncallbackFn
  • *[]thisArg

参数

callbackFn

回调函数。该回调函数接受3个参数。其原型如下:

booleancallbackFn
  • *element
  • numberindex
  • *[]array
element
当前遍历到的数组元素。
index
当前遍历到的数组索引值。
array
调用findIndex方法的数组实例。

回调函数callbackFn返回boolean类型的数值。

thisArg
调用findIndex方法的数组实例。可选。

返回值

如果有满足回调函数所设定条件的元素,则返回第一个元素所在的索引值。

如果所有元素均未满足回调函数所设定的条件,则返回-1

说明

findIndex方法通过调用回调函数来遍历数组元素,并在回调函数中设定一个适用于数组全体元素的条件。

如果有至少一个元素满足回调函数所设定的条件,则返回满足条件的第一个元素所在的索引值。如果所有元素均未满足回调函数所设定的条件,则返回-1

例子

基本用法

import {NumUtils} from '/js/esm/NumUtils.js'; let nums = NumUtils.GetIntsInRange(-100, 100, 5); /* [84, -35, 7, -78, 31] */ let index = nums.findIndex(num => num < 0); /* 1 */

未能满足条件时返回-1

let nums = [1, 2, 3, 4, 5]; let index = nums.findIndex(num => num < 0); /* -1 */

参见

  1. find
  2. findLastIndex

参考资源

  1. ECMA 262: Array Objects