JavaScript Array forEach () yöntemi, her dizi öğesi için sağlanan bir işlevi yürütür.
forEach()
Yöntemin sözdizimi şöyledir:
arr.forEach(callback(currentValue), thisArg)
Burada dizi bir dizidir.
forEach () Parametreleri
forEach()
Yöntem alır:
- callback - Her dizi öğesinde çalıştırılacak işlev. Alır:
- currentValue - Diziden iletilmekte olan geçerli öğe.
- thisArg (isteğe bağlı) -
this
Geri aramayı yürütürken olduğu gibi kullanılacak değer . Varsayılan olarak öyleundefined
.
ForEach () öğesinden dönüş değeri
- İade
undefined
.
Notlar :
forEach()
orijinal diziyi değiştirmez.forEach()
callback
sırayla her dizi elemanı için bir kez çalıştırılır .forEach()
callback
değerleri olmayan dizi öğeleri için çalıştırılmaz .
Örnek 1: Dizi İçeriklerini Yazdırma
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);
Çıktı
Dizi Öğesi 0: 1800 Dizi Öğesi 1: 2000 Dizi Öğesi 2: 3000 Dizi Öğesi 4: 5000 Dizi Öğesi 5: 500 Dizi Öğesi 6: 8000
Örnek 2: thisArg'ı kullanma
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
Çıktı
4 58 1440
Burada yine forEach
boş elementi atladığını görebiliriz . Counter nesnesinin yönteminin tanımının içinde thisArg
olduğu gibi geçirilir .this
execute
Önerilen Kaynaklar: JavaScript Dizi haritası ()