English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript array findIndex() method

 مثلث JavaScript Array

findIndex()The method returns the index of the first element in the array that meets the provided test function.

findIndex()The method calls the function to execute once for each element in the array:

  • When the elements in the array return true when testing the condition, findIndex() returns the index position of the element that meets the conditions, and the subsequent values will not call the execution function

  • If there is no element that meets the conditions, -1 is returned

note: The findIndex() method does not change the original array.

note: The function will not be executed for an empty array in findIndex().

syntax:

array.findIndex(callback, thisArg)
array.findIndex(function(element, index, arr), thisArg)
var num = [1, 30, 39, 29, 10, 13];
var val = num.findIndex(myFunc);
function myFunc(element) {
return element >= 18;
}
اختبار لرؤية‹/›

see alsofind()A method that returns the value of the element found in the array instead of its index.

browser compatibility

The numbers in the table specify the first browser version that fully supports the findIndex() method:

Method
findIndex()452532812

parameter value

parametersdescription
callback
The function run for each element in the array.
function parameters:
  • element(required) - The current element being processed in the array

  • index(optional) - The index of the current element in the array being processed

  • arr(optional) - Optional. The array object to which the current element belongs

thisArgoptional. The value passed to the function is generally the "this" value.
if this parameter is empty, "undefined" will be passed to the "this" value

technical details

return value:if the element passes the test, it isindex؛else-1
إصدار JavaScript:ECMAScript 6

مزيد من الأمثلة

في هذا المثال، يعود العنصر إلى indexer العنصر في البنية التي هو عدد أولي؛ إذا لم يكن هناك عدد أولي، فيرجع إلى -1:

var array1 = [1, 15, 17, 24, 29, 10, 13];
function isPrime(element) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
     if (element % start < 1) {
         return false;
     } else {
         start++;
     }
  }
  return element > 1;
}
function myFunc1() {
   document.getElementById("result").innerHTML = array1.findIndex(isPrime);
}
اختبار لرؤية‹/›

 مثلث JavaScript Array