Metoda JavaScript Array forEach () provádí poskytovanou funkci pro každý prvek pole.
Syntaxe forEach()
metody je:
arr.forEach(callback(currentValue), thisArg)
Zde je arr pole.
parametry forEach ()
forEach()
Metoda bere v:
- zpětné volání - funkce, která se má provést na každém prvku pole. Trvá:
- currentValue - aktuální prvek předávaný z pole.
- thisArg (volitelně) - hodnota, která se použije jako
this
při provádění zpětného volání. Ve výchozím nastavení jeundefined
.
Vrátit hodnotu z forEach ()
- Vrací se
undefined
.
Poznámky :
forEach()
nezmění původní pole.forEach()
provedecallback
se pro každý prvek pole v pořadí.forEach()
neprovádícallback
pro prvky pole bez hodnot.
Příklad 1: Tisk obsahu pole
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);
Výstup
Array Element 0: 1800 Array Element 1: 2000 Array Element 2: 3000 Array Element 4: 5000 Array Element 5: 500 Array Element 6: 8000
Příklad 2: Použití 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
Výstup
4 58 1440
Zde opět vidíme, že forEach
přeskočí prázdný prvek. thisArg
je předán jako this
uvnitř definice execute
metody objektu Counter.
Doporučené čtení: Mapa pole JavaScript ()