0

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?

asked Apr 15, 2013 at 9:08
1

3 Answers 3

2

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); }
);
answered Apr 15, 2013 at 9:11
Sign up to request clarification or add additional context in comments.

11 Comments

Try "abc".forEach(function(v){console.log(v)}). You'd have to use apply or call.
@dystroy — Yes, you have to use apply or call. That doesn't mean you can't use it.
@Quentin I agree (and I didn't downvote). I simply think this should be clearer.
@Quentin i agree too, with the use of call and apply it works but is it only for Nodelist?
@Maizere - No, any array-like object, e.g., it would work on this object: {"0":10,"1":20,"length":2}.
|
1

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.

answered Apr 15, 2013 at 9:10

1 Comment

Just for good reading as well! stackoverflow.com/questions/500504/…
-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

2 Comments

Did you mean to post to Stack Overflow en español?
Code formatting

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.