Array Javascript paraEach ()

O método JavaScript Array forEach () executa uma função fornecida para cada elemento do array.

A sintaxe do forEach()método é:

 arr.forEach(callback(currentValue), thisArg)

Aqui, arr é um array.

Parâmetros forEach ()

O forEach()método inclui:

  • callback - A função a ser executada em cada elemento da matriz. Inclui:
    • currentValue - O elemento atual que está sendo passado da matriz.
  • thisArg (opcional) - Valor a ser usado thisao executar o retorno de chamada. Por padrão, é undefined.

Valor de retorno de forEach ()

  • Retorna undefined.

Notas :

  • forEach() não altera a matriz original.
  • forEach()é executado callbackuma vez para cada elemento da matriz em ordem.
  • forEach()não é executado callbackpara elementos da matriz sem valores.

Exemplo 1: Imprimindo o conteúdo da matriz

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

Resultado

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

Exemplo 2: Usando esteArg

 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

Resultado

 4 58 1440

Aqui, podemos ver novamente que forEachignora o elemento vazio. thisArgé passado como thisdentro da definição do executemétodo do objeto Counter.

Leitura recomendada: JavaScript Array map ()

Artigos interessantes...