The Ashes

Technology, Science and other news
April 25, 2009

How many ways can you iterate over an array in JavaScript?

Posted by : admin
Filed under : General

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:

for each in:

JAVASCRIPT:

  1.  
  2. for each (var item in [1, 2, 3]) alert(item);
  3.  

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. [1, 2, 3].forEach(function(item) { alert(item) });
  3.  

JavaScript 1.7 added array comprehensions for array initialization:

JAVASCRIPT:

  1.  
  2. var squares = [item * item for each (item in [1, 2, 3])];
  3.  

I just realized I can (ab)use comprehensions to iterate arrays with Perl-like syntax by throwing away the result:

JAVASCRIPT:

  1.  
  2. [alert(item) for each (item in [1, 2, 3])];
  3.  

I can iterate object properties the same way:

JAVASCRIPT:

  1.  
  2. var obj = { foo: 1, bar: 2, baz: 3 };
  3. [alert(name + “=” + obj[name]) for (name in obj)];
  4.  

Edward Lee points out how to use Iterators:

JAVASCRIPT:

  1.  
  2. [alert(key + “=” + val) for ([key, val] in Iterator({a:1,b:2,c:3}))]
  3.  
Tags :

No Comments

(required)
(will not be published) (required)
(opitional)

cciash.com EN ES IT DE PT CZ FR RU
February 2018
M T W T F S S
« Sep    
 1234
567891011
12131415161718
19202122232425
262728  

Pages

Categories

Resources

There are many online poker site where you can play but at poker.hk you can play the poker games with all the knowledge you need related to the game with the poker school available in both the English and Chinese language.

Super Casino

Now you can bet on any sports and any sporting events from all the comfort from your home. Bet770 allows you to bet on any events and match with in just 3 clicks. They also offers great odds on football betting for every premier and champions league match. Get £50 free in bets when you register.

Bingo770, offering best online bingo games with £7.70 free no deposit Bonus!