JavaScript 中 Array.findIndex() 方法有什么作用?
数组是一种可以存储多个相同数据类型元素的数据类型。例如,如果数组声明为整型数据类型,则它存储一个或多个整型数据类型元素。
在 JavaScript 中,数组是对象,这些对象具有一些内置函数和属性,可以使用它们更快、更容易地进行操作。
本教程解释并演示了数组对象“findIndex()”的功能,并提供了一些示例。
JavaScript 数组中的“findIndex()”方法将返回给定数组中满足给定约束条件的第一个元素。即使有两个或多个数字,此方法也会返回给定数组中第一个元素的索引。如果不存在满足给定约束条件或条件的元素,则返回 -1。
语法
findIndex() 方法的语法如下:
array.findIndex(function(element, index, array), thisArg)
上面给出的语法称为内联回调函数语法,因为函数和其他参数都是一次性在一行中调用的。
“findIndex()”方法将接收包括函数在内的五个参数。它们是:
函数 - 该函数用于对数组的所有元素执行操作,直到满足约束条件并返回 true。
元素 - 这是数组中当前正在进行给定功能或约束的元素。
索引 - 这是一个可选参数,可以访问数组中当前元素的索引。
数组 - 这是一个可选参数,其值为包含当前元素的给定数组对象。
thisArg - 这是一个可选参数,如果传递则用作“this”的值,如果不传递则默认为“undefined”。
如果给定数组中存在元素并满足条件,则返回元素的索引;否则返回“-1”。
示例 1
下面的示例演示了在 JavaScript 中使用 findIndex() 方法。在这里,我们尝试检索给定数组中的偶数:
function isEven(element) { return element % 2 == 0; } let arr = [7, 8, 1, 3, 4]; let firstEvenNumber = arr.findIndex(isEven); console.log("The given array is:",arr) console.log("The first even numbers index in the given array is:",firstEvenNumber); console.log("The first even number at the returned index is:",arr[firstEvenNumber])
示例 2
让我们来看另一个示例,在这里我们打印给定数组中大于 45 的元素。
var arr = [11, 23, 36, 156, 58]; function findIndex(element) { return element > 45; } var v = arr.findIndex(findIndex) console.log("The given array is:",arr) console.log("The first numbers index in the given array which satisfies the constraint is:",v) console.log("The first number in the given array at the returned index is:",arr[v])
示例 3
下面的示例以箭头函数的形式使用 findIndex():
let employee = ["Abdul", "Badavath", "Yadav", "Taruni"]; let index = employee.findIndex((day) => day === "Taruni"); console.log("The given array is:",employee) console.log("The index of the given element is:",index) console.log("The element at the returned index is:",employee[index])
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP