JavaScript Array findIndex ()

Il metodo findIndex () di JavaScript Array restituisce l'indice del primo elemento dell'array che soddisfa la funzione di test fornita oppure restituisce -1.

La sintassi del findIndex()metodo è:

 arr.findIndex(callback(element, index, arr),thisArg)

Qui, arr è un array.

parametri findIndex ()

Il findIndex()metodo comprende:

  • callback - Funzione da eseguire su ogni elemento dell'array. Comprende:
    • element - L'elemento corrente di array.
  • thisArg (opzionale) - Oggetto da utilizzare come thiscallback interno.

Valore restituito da findIndex ()

  • Restituisce l' indice del primo elemento dell'array che soddisfa la funzione data.
  • Restituisce -1 se nessuno degli elementi soddisfa la funzione.

Esempio 1: utilizzo del metodo findIndex ()

 function isEven(element) ( return element % 2 == 0; ) let randomArray = (1, 45, 8, 98, 7); firstEven = randomArray.findIndex(isEven); console.log(firstEven); // 2 // using arrow operator firstOdd = randomArray.findIndex((element) => element % 2 == 1); console.log(firstOdd); // 0

Produzione

 2 0

Esempio 2: findIndex () con elementi Object

 const team = ( ( name: "Bill", age: 10 ), ( name: "Linus", age: 15 ), ( name: "Alan", age: 20 ), ( name: "Steve", age: 34 ), ); function isAdult(member) ( return member.age>= 18; ) console.log(team.findIndex(isAdult)); // 2 // using arrow function and deconstructing adultMember = team.findIndex((( age )) => age>= 18); console.log(adultMember); // 2 // returns -1 if none satisfy the function infantMember = team.findIndex((( age )) => age <= 1); console.log(infantMember); // -1

Produzione

 2 2-1

Letture consigliate: JavaScript Array find ()

Articoli interessanti...