Die JavaScript Array forEach () -Methode führt für jedes Array-Element eine bereitgestellte Funktion aus.
Die Syntax der forEach()
Methode lautet:
arr.forEach(callback(currentValue), thisArg)
Hier ist arr ein Array.
forEach () -Parameter
Die forEach()
Methode umfasst:
- Rückruf - Die Funktion, die für jedes Array-Element ausgeführt werden soll. Es dauert:
- currentValue - Das aktuelle Element, das vom Array übergeben wird.
- thisArg (optional) - Wert, der
this
beim Ausführen eines Rückrufs verwendet werden soll. Standardmäßig ist esundefined
.
Rückgabewert von forEach ()
- Rückgabe
undefined
.
Anmerkungen :
forEach()
ändert das ursprüngliche Array nicht.forEach()
wirdcallback
einmal für jedes Array-Element der Reihe nach ausgeführt.forEach()
wird nichtcallback
für Array-Elemente ohne Werte ausgeführt.
Beispiel 1: Drucken des Inhalts eines Arrays
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);
Ausgabe
Array-Element 0: 1800 Array-Element 1: 2000 Array-Element 2: 3000 Array-Element 4: 5000 Array-Element 5: 500 Array-Element 6: 8000
Beispiel 2: Verwenden von thisArg
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
Ausgabe
4 58 1440
Hier können wir wieder sehen, dass forEach
das leere Element übersprungen wird. thisArg
wird wie this
in der Definition der execute
Methode des Counter-Objekts übergeben.
Empfohlene Lektüre: JavaScript Array map ()