Tableau JavaScript trouver ()

La méthode JavaScript Array find () renvoie la valeur du premier élément de tableau qui satisfait la fonction de test fournie.

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

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

Ici, arr est un tableau.

Paramètres find ()

La find()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 find ()

  • Renvoie la valeur du premier élément du tableau qui satisfait la fonction donnée.
  • Renvoie undefined si aucun des éléments ne satisfait la fonction.

Exemple 1: Utilisation de la méthode find ()

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

Production

 8 1

Exemple 2: find () 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.find(isAdult)); // ( name: 'Alan', age: 20 ) // using arrow function and deconstructing adultMember = team.find((( age )) => age>= 18); console.log(adultMember); // ( name: 'Alan', age: 20 )

Production

 (nom: 'Alan', âge: 20) (nom: 'Alan', âge: 20)

Lecture recommandée: JavaScript Array.findIndex ()

Articles intéressants...