Snippet – C#, JavaScript, jQuery, Underscore ForEach Loops

10063_580983808600819_401360548_nThe foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the information that you want.

It is not be used to add or remove items from the source collection to avoid unpredictable side effects. (If you need to add or remove items from the source collection, use a for loop.)

C# foreach

In C# I can use a foreach loop on the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T>.

So my C# code looks like this:

JavaScript for Loop

But JavaScript lacks a specific foreach statement. Instead, you use a for loop. And this code looks similar to the code you would use in a for loop in C# but without the types.

Results in

0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13

jQuery Foreach Loops

jQuery makes the concept of a foreach loop simpler. To iterate over an array in jQuery, use the jQuery.each() (or in shorthand, $.each()) function.

The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Note: This is a different function than the more commonly known $(whatever_element).each(), which you use to iterate over a jQuery object.

Results in

0
1
1
2
3
5
8
13

In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.)

You can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Underscore Each

each_.each(list, iteratee, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee‘s arguments will be (value, key, list). Returns the list for chaining.

Results in

0
1
1
2
3
5
8
13
"1: one"
"2: two"
"3: three"

References

How To Emulate a Foreach Loop in JavaScript

jQuery.each() in the jQuery API Documentation

foreach, in (C# Reference) on MSDN

How to loop through array in jquery

Advertisements