JavaScript Array forEach () metode izpilda paredzēto funkciju katram masīva elementam.
Metodes sintakse forEach()
ir šāda:
arr.forEach(callback(currentValue), thisArg)
Lūk, arr ir masīvs.
forEach () parametri
forEach()
Metode ņem in:
- atzvanīšana - funkcija, kas jāizpilda katram masīva elementam. Tas aizņem:
- currentValue - pašreizējais elements, kas tiek nodots no masīva.
- thisArg (pēc izvēles) - vērtība, kas jāizmanto kā
this
, veicot atzvanīšanu. Pēc noklusējuma tā irundefined
.
Atgriezt vērtību no forEach ()
- Atgriežas
undefined
.
Piezīmes :
forEach()
nemaina sākotnējo masīvu.forEach()
izpildacallback
vienu reizi katram masīva elementam secībā.forEach()
neizpildacallback
masīva elementiem bez vērtībām.
1. piemērs: Masīva satura drukāšana
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);
Rezultāts
Masīvs elements 0: 1800 Masīvs elements 1: 2000 Masīvs elements 2: 3000 Masīvs elements 4: 5000 Masīvs elements 5: 500 Masīvs elements 6: 8000
2. piemērs: thisArg izmantošana
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
Rezultāts
4 58 1440
Šeit mēs atkal varam redzēt, ka tiek forEach
izlaists tukšais elements. thisArg
tiek nodots kā Counter objekta metodes this
definīcijas iekšpusē execute
.
Ieteicamā literatūra: JavaScript masīva karte ()