U ovom ćete uputstvu uz primjere naučiti o metodi JavaScript forEach ().
forEach()
Metoda naziva funkcije i iterira kroz elemente niza. forEach()
Metoda može se koristiti na kartama i postavlja.
JavaScript za svaki
Sintaksa forEach()
metode je:
array.forEach(function(currentValue, index, arr))
Ovdje,
- funkcija (currentValue, index, arr) - funkcija koja se pokreće za svaki element niza
- currentValue - vrijednost niza
- indeks (neobavezno) - indeks trenutnog elementa
arr (nije obavezno) - niz trenutnih elemenata
forSvaki s nizovima
forEach()
Metoda se koristi za prolazak kroz niz. Na primjer,
let students = ('John', 'Sara', 'Jack'); // using forEach students.forEach(myFunction); function myFunction(item) ( console.log(item); )
Izlaz
John Sara Jack
U gornjem programu forEach()
metoda preuzima myFunction()
funkciju koja prikazuje svaki element niza učenika.
Ažuriranje elemenata niza
Kao što smo vidjeli u gornjem primjeru, forEach()
metoda se koristi za iteraciju preko niza, vrlo je jednostavno ažurirati elemente niza. Na primjer,
let students = ('John', 'Sara', 'Jack'); // using forEach students.forEach(myFunction); function myFunction(item, index, arr) ( // adding strings to the array elements arr(index) = 'Hello ' + item; ) console.log(students);
Izlaz
("Zdravo John", "Zdravo Sara", "Zdravo Jack")
forEach s funkcijom strelice
Pomoću metode strelice možete koristiti forEach()
metodu za pisanje programa. Na primjer,
// with arrow function and callback const students = ('John', 'Sara', 'Jack'); students.forEach(element => ( console.log(element); ));
Izlaz
John Sara Jack
za petlju za forEach ()
Evo primjera kako možemo napisati program s for
loopom i with forEach()
.
Korištenje for petlje
const arrayItems = ('item1', 'item2', 'item3'); const copyItems = (); // using for loop for (let i = 0; i < arrayItems.length; i++) ( copyItems.push(arrayItems(i)); ) console.log(copyItems);
Izlaz
("stavka1", "stavka2", "stavka3")
Korištenje forEach ()
const arrayItems = ('item1', 'item2', 'item3'); const copyItems = (); // using forEach arrayItems.forEach(function(item)( copyItems.push(item); )) console.log(copyItems);
za … od sa Setovima
Pomoću forEach()
metode možete prelaziti kroz elemente Set . Na primjer,
// define Set const set = new Set((1, 2, 3)); // looping through Set set.forEach(myFunction); function myFunction(item) ( console.log(item); )
Izlaz
1 2 3
forEach s kartama
Pomoću forEach()
metode možete prelistavati elemente karte . Na primjer,
let map = new Map(); // inserting elements map.set('name', 'Jack'); map.set('age', '27'); // looping through Map map.forEach (myFunction); function myFunction(value, key) ( console.log(key + '- ' + value); )
Izlaz
ime- Jack dob- 27