Javascript-array voor elke ()

De JavaScript-methode Array forEach () voert een opgegeven functie uit voor elk array-element.

De syntaxis van de forEach()methode is:

 arr.forEach(callback(currentValue), thisArg)

Hier is arr een array.

forEach () Parameters

De forEach()methode omvat:

  • callback - De functie die op elk array-element moet worden uitgevoerd. Het duurt:
    • currentValue - Het huidige element dat wordt doorgegeven vanuit de array.
  • thisArg (optioneel) - Waarde die moet worden gebruikt als thisbij het uitvoeren van callback. Standaard is het undefined.

Retourwaarde van forEach ()

  • Retourneert undefined.

Opmerkingen :

  • forEach() verandert de originele array niet.
  • forEach()wordt callbackeenmaal uitgevoerd voor elk array-element in volgorde.
  • forEach()wordt niet uitgevoerd callbackvoor matrixelementen zonder waarden.

Voorbeeld 1: inhoud van array afdrukken

 function printElements(element, index) ( console.log('Array Element ' + index + ': ' + element); ) const prices = (1800, 2000, 3000, , 5000, 500, 8000); // forEach does not execute for elements without values // in this case, it skips the third element as it is empty prices.forEach(printElements);

Uitvoer

 Array-element 0: 1800 Array-element 1: 2000 Array-element 2: 3000 Array-element 4: 5000 Array-element 5: 500 Array-element 6: 8000

Voorbeeld 2: ThisArg gebruiken

 function Counter() ( this.count = 0; this.sum = 0; this.product = 1; ) Counter.prototype.execute = function (array) ( array.forEach((entry) => ( this.sum += entry; ++this.count; this.product *= entry; ), this) ) const obj = new Counter(); obj.execute((4, 1, , 45, 8)); console.log(obj.count); // 4 console.log(obj.sum); // 58 console.log(obj.product); // 1440

Uitvoer

 4 58 1440

Hier kunnen we opnieuw zien dat forEachhet lege element overslaat. thisArgwordt doorgegeven als thisbinnen de definitie van de executemethode van het Counter-object.

Aanbevolen literatuur: JavaScript-matrixkaart ()

Interessante artikelen...