The Ashes
How many ways can you iterate over an array in JavaScript?
Myk is one of the nicest chaps that I have had the pleasure to sit closely to in Mozilla building “S”.
He has a nice little tip on the many syntaxes that you can use to iterate over arrays in various JavaScript implementations and standards. Some folks had some interesting points on the various approaches:
JAVASCRIPT:
for each (var item in [1, 2, 3]) alert(item);The MDC docs for “for each” say not to iterate arrays that way, too, so I never use it on them. The usual (would need to guard with
hasOwnProperty()
issue).JavaScript 1.6 added the Array.forEach method:
JAVASCRIPT:
[1, 2, 3].forEach(function(item) { alert(item) });JavaScript 1.7 added array comprehensions for array initialization:
JAVASCRIPT:
var squares = [item * item for each (item in [1, 2, 3])];I just realized I can (ab)use comprehensions to iterate arrays with Perl-like syntax by throwing away the result:
JAVASCRIPT:
[alert(item) for each (item in [1, 2, 3])];I can iterate object properties the same way:
JAVASCRIPT:
var obj = { foo: 1, bar: 2, baz: 3 }; [alert(name + “=” + obj[name]) for (name in obj)];Edward Lee points out how to use Iterators:
JAVASCRIPT:
[alert(key + “=” + val) for ([key, val] in Iterator({a:1,b:2,c:3}))]
No Comments