A JavaScript Array forEach () metódus végrehajt egy megadott függvényt minden tömb elemhez.
A forEach()
módszer szintaxisa :
arr.forEach(callback(currentValue), thisArg)
Itt az arr egy tömb.
forEach () paraméterek
A forEach()
módszer:
- visszahívás - Minden tömbelemen végrehajtandó funkció. Beletelik:
- currentValue - A tömbből átadott aktuális elem.
- thisArg (opcionális) -
this
Visszahívás végrehajtásakor használandó érték . Alapértelmezés szerint azundefined
.
Visszatérési érték a forEach () alapján
- Visszatér
undefined
.
Megjegyzések :
forEach()
nem változtatja meg az eredeti tömböt.forEach()
callback
minden tömb elemnél egyszer végrehajt .forEach()
callback
értékek nélküli tömbelemekre nem hajt végre .
1. példa: A tömb tartalmának kinyomtatása
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);
Kimenet
Tömbelem 0: 1800 tömbelem 1: 2000 tömbelem 2: 3000 tömbelem 4: 5000 tömbelem 5: 500 tömbelem 6: 8000
2. példa: Az thisArg használata
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
Kimenet
4 58 1440
Itt ismét láthatjuk, hogy forEach
kihagyja az üres elemet. a Counter objektum metódusának meghatározásán belül thisArg
kerül átadásra .this
execute
Ajánlott olvasmány: JavaScript tömb térkép ()