Metóda JavaScript Array findIndex () vráti index prvého prvku poľa, ktorý spĺňa poskytnutú testovaciu funkciu, alebo vráti -1.
Syntax findIndex()
metódy je:
arr.findIndex(callback(element, index, arr),thisArg)
Tu je arr pole.
parametre findIndex ()
findIndex()
Metóda berie v:
- spätné volanie - funkcia, ktorá sa má vykonať na každom prvku poľa. Trvá to:
- element - Aktuálny prvok poľa.
- thisArg (voliteľné) - Objekt, ktorý sa má použiť ako
this
spätné volanie.
Vrátiť hodnotu z findIndex ()
- Vracia index na prvý prvok v poli, ktorý spĺňa daná funkcia.
- Vráti hodnotu -1, ak žiadny z prvkov nespĺňa funkciu.
Príklad 1: Použitie metódy 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
Výkon
2 0
Príklad 2: findIndex () s prvkami 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
Výkon
2 2 -1
Odporúčané čítanie: Nájsť pole JavaScriptu ()