Javascript forEach() Metodu
ES5
forEach()
metodu, dizideki her elemanı bir işlevden geçirir. Kısaca döngüye sokmanızı sağlar.
Yapısı (Syntax)array.forEach(function(currentValue, index, arr), thisValue)
Parametreler
-
currentValueİşlemden geçen elemanın değeri
-
indexİşlemden geçen elemanın indis değeri
-
arrİşlemden geçen elemanın ait olduğu dizi
Örnekler
Boş değerler işleme alınmaz
const array = [1,3,,7]
let numCallbackRuns = 0
array.forEach(el => {
console.log(el)
numCallbackRuns++
})
console.log("numCallbackRuns: ", numCallbackRuns)
// 1
// 3
// 7
// numCallbackRuns: 3
// gördüğünüz gibi 3 ve 7 arasındaki başlatılmamıboş değerler sayılmadı
For döngüsünü forEach'e çevirme
const items = ['item1', 'item2', 'item3']
const copyItems = []
// öncesi
for (let i = 0; i < items.length; i++) {
copyItems.push(items[i])
}
// sonrası
items.forEach(function(item){
copyItems.push(item)
})
thisArg
kullanımı
function Counter() {
this.sum = 0
this.count = 0
}
Counter.prototype.add = function(array) {
array.forEach(entry => {
this.sum += entry
++this.count
}, this)
}
const obj = new Counter()
obj.add([2, 5, 9])
console.log(obj.count)
// 3
console.log(obj.sum)
// 16
Döngüdeyken dizide değişiklik yapmak
Döngü içinde two
değerine geldiğinde, unshift()
ile dizinin ilk değeri silinecek. Ve two
değerinden sonraki değerlerin indisi birer azalacağı için 3. yü pas geçerek dördüncüden devam edecek.
let words = ['one', 'two', 'three', 'four']
words.forEach((word) => {
console.log(word)
if (word === 'two') {
words.shift() //'one' diziden silinecek
}
}) // one // two // four
console.log(words); //['two', 'three', 'four']
İç içe dizileri düzleştirmek
Aşağıdaki örnek forEach()
metodunu öğrenme amaçlı hazırlanmıştır. Bu işlem için zaten flat() metodu kullanılmaktadır.
function flatten(arr) {
const result = []
arr.forEach((i) => {
if (Array.isArray(i)) {
result.push(...flatten(i))
} else {
result.push(i)
}
})
return result
}
// Kullanımı
const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
console.log(flatten(nested)) // [1, 2, 3, 4, 5, 6, 7, 8, 9]