Maizere Pathak.Nepal
Maizere Pathak.Nepal

Reputation: 2411

Using forEach method in javascript

Is forEach method designed to work for only array in javascript?Can anyone share idea or an example on what major task can be completed with forEach() method or is it useful for only getting element value and index?

Upvotes: 0

Views: 219

Answers (3)

Harol Rodrígue
Harol Rodrígue

Reputation: 1

The forEach method in JavaScript allows you to traverse an array and apply a particular action to each of its elements through a function. Let's see an example:

array.forEach(function(elementoActual, indice, array))

elmentoActual: es el valor del elemento actual del array. índice: es el índice del elemento actual del array (opcional). array: es el array que se está recorriendo (opcional).

For more information I leave the following article https://4geeks.com/es/how-to/metodo-foreach-javascript

Upvotes: -1

Denys Séguret
Denys Séguret

Reputation: 382514

It is an Array function. See documentation

You can use it on any array-like object but it's not very convenient because you have to use apply or call. For example :

[].forEach.call("abc",function(v){console.log(v)})

To iterate over objects keys, you should use for..in :

for (key in object) {
    var value = object[key];
} 

Note that jQuery's compatibility function $.each enables the same iteration function for both arrays and non array objects but you generally know if you're dealing with an array (or you should) so I'd use it only for compatibility with old browsers.

Upvotes: 1

Quentin
Quentin

Reputation: 944564

No.

It is designed to work on arrays, but can operate on any array-like object (although you still have to access it from somewhere where it exists).

For example, on a NodeList:

Array.prototype.forEach.call(
    document.getElementsByTagName('div'), 
    function (divElement) { console.log(divElement); }
);

Upvotes: 2

Related Questions