„JavaScript Array forEach“ () metodas vykdo numatytą funkciją kiekvienam masyvo elementui.
forEach()
Metodo sintaksė yra tokia:
arr.forEach(callback(currentValue), thisArg)
Čia arr yra masyvas.
forEach () parametrai
forEach()
Metodas trunka:
- atgalinis skambutis - funkcija, vykdoma kiekviename masyvo elemente. Tai užima:
- currentValue - dabartinis elementas, perduodamas iš masyvo.
- „thisArg“ (neprivaloma) - vertė, naudojama kaip
this
vykdant atgalinį skambutį. Pagal nutylėjimą taip yraundefined
.
Grąžinimo vertė iš forEach ()
- Grįžta
undefined
.
Pastabos :
forEach()
nekeičia pradinio masyvo.forEach()
vykdocallback
vieną kartą kiekvienam masyvo elementui eilės tvarka.forEach()
nevykdocallback
masyvo elementų be reikšmių.
1 pavyzdys: Masyvo turinio spausdinimas
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);
Rezultatas
Masyvo elementas 0: 1800 Masyvo elementas 1: 2000 Masyvo elementas 2: 3000 Masyvo elementas 4: 5000 Masyvo elementas 5: 500 Masyvo elementas 6: 8000
2 pavyzdys: „thisArg“ naudojimas
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
Rezultatas
4 58 1440
Čia vėl galime pamatyti, kad forEach
praleidžiamas tuščias elementas. thisArg
yra perduodamas kaip skaitiklio objekto metodo this
apibrėžimas execute
.
Rekomenduojamas skaitymas: „ Java“ masyvo žemėlapis ()