foreach -配列関数


ループは、プロジェクト開発の重要な一部です.私たちは、ループのための基本がコードの特定のセットを実行するためにコードを反復する必要があります.foreachおよびmap関数は、配列に存在する各要素の関数を反復処理するのに役立ちます.

foreach
Syntax : 

array.forEach(callback(item, index, array), thisVar)

array - contains the list of elements for which we want to run the callback function
item - (*optional*) Each item is passed to the function as an argument.
index - (*optional*) Contains the index of the element that is passed as an argument.
thisVar - (*optional*) Used to set the context for the given function, upper scope. It is not needed if we use the arrow functions

Note - The return value is "undefined"
forech ()関数を停止したり中断したりする方法はありません.このような振る舞いをしたい場合は、単純なループを使用して実現できます.…のために.あるいはその他のarray function ()関数、some()、find ()、findindev ()のいずれかです.
また、foreachは非同期関数を説明しないので注意しなければなりません.したがって、API呼び出しの間、それを避けるほうがよいです.

初期化値の操作はありません
const array = ["Hello","World",,"skipped uninitialized value"]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// Hello
// World
// skipped uninitialized value
// numCallbackRuns: 3
// the missing value between "World" and "skipped uninitialized value" didn't invoke the callback function. Even if it would have been a "", it would have a count

ループをforeachに変換する
const shop = ['banana', 'rice', 'pulses']
const copyItems = []

// before
for (let i = 0; i < shop.length; i++) {
  copyItems.push(shop[i])
}

// after
shop.forEach(function(item){
  copyItems.push(item)
})