Javascript polje zaEach ()

Metoda JavaScript Array forEach () izvrši predvideno funkcijo za vsak element matrike.

Sintaksa forEach()metode je:

 arr.forEach(callback(currentValue), thisArg)

Tu je arr matrika.

forEach () parametri

forEach()Metoda je v:

  • povratni klic - funkcija za izvajanje na vsakem elementu matrike. Vključuje:
    • currentValue - trenutni element, ki se prenaša iz polja.
  • thisArg (neobvezno) - vrednost, ki se uporablja kot thispri izvajanju povratnega klica. Privzeto je undefined.

Vrnjena vrednost iz forEach ()

  • Vrne undefined.

Opombe :

  • forEach() ne spremeni prvotnega polja.
  • forEach()se izvede callbackenkrat za vsak element matrike po vrsti.
  • forEach()se ne izvede callbackza elemente matrike brez vrednosti.

Primer 1: Tiskanje vsebine matrike

 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);

Izhod

 Element polja 0: 1800 Element polja 1: 2000 Element polja 2: 3000 Element polja 4: 5000 Element polja 5: 500 Element polja 6: 8000

Primer 2: Uporaba tega Arg

 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

Izhod

 4 58 1440

Tu lahko spet vidimo, da forEachpreskoči prazen element. thisArgse posreduje kot thisznotraj definicije executemetode predmeta Counter.

Priporočeno branje: Zemljevid matrike JavaScript ()

Zanimive Članki...