Prototype Tutorial followup: Enumerable and Hash

Wednesday, February 22nd, 2006 @ 3:59 pm | filed under: Code Snippets, Examples, Optimization, Organizing Code, Prototype, Reference

At the bottom of the prototype tutorial I just posted is this great article on Encytemedia.com that digs into the Enumerable and Hash functions of the library in greater detail. There’s a lot of great stuff in here.

each and friends

I used to find myself writing a lot of for loops. Although, Prototype doesn’t by any means eliminate the need to do for loops, it does give you access to what I consider to be a cleaner, easier to read method in each.

for(var i = 0; i < F.Numbers.length; i++) {
  logger.info(F.Numbers[i]);
}

each allows us to iterate over these objects Ruby style.

F.Numbers.each(function(num) {
  logger.info(num);
});

//Output
0
1
4
5
98
32
12
9

each takes one argument, the iterator or block in Ruby terms. This iterator is invoked once for every item in the array, and that item along with the optional index is passed to the iterator. So if we also needed the index we could do something like the code below.

F.Numbers.each(function(num, index) {
  logger.info(index + ": " + num);
});

//Output
0: 0
1: 1
2: 4
3: 5
4: 98
5: 32
6: 12
7: 9
No TweetBacks yet. (Be the first to Tweet this post)

Comments are closed.