Prototype Tutorial followup: Enumerable and Hash
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 9each 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
Follow @clientcide on twitter to get notified of new posts.
To follow me personally on twitter, follow @anutron.