Tableau JavaScript findIndex ()

La méthode JavaScript Array findIndex () renvoie l'index du premier élément du tableau qui satisfait la fonction de test fournie ou renvoie -1.

La syntaxe de la findIndex()méthode est:

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

Ici, arr est un tableau.

Paramètres findIndex ()

La findIndex()méthode prend en compte:

  • callback - Fonction à exécuter sur chaque élément du tableau. Il prend en:
    • element - L'élément actuel du tableau.
  • thisArg (facultatif) - Objet à utiliser comme thisrappel interne.

Valeur renvoyée par findIndex ()

  • Renvoie l' index du premier élément du tableau qui satisfait la fonction donnée.
  • Renvoie -1 si aucun des éléments ne satisfait la fonction.

Exemple 1: Utilisation de la méthode 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

Production

 2 0

Exemple 2: findIndex () avec des éléments 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

Production

 2 2 -1

Lecture recommandée: JavaScript Array find ()

Articles intéressants...