Posted By

arunpjohny on 11/05/09


Tagged

javascript array


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

arunpjohny


Array.each function


 / Published in: JavaScript
 

This function is add 'each' function to the javascript Array object.

  1. if(typeof Array.prototype.each != 'function'){
  2. Array.prototype.each = function(callback, context){
  3. if(this.length > 0 && typeof callback == 'function'){
  4. for(var i = 0; i < this.length; i++){
  5. callback.call(context || window, this[i]);
  6. }
  7. }
  8. }
  9. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: arunpjohny on November 5, 2009

The above code can be tested using the following html page

    Testing Array.each function.


    if(typeof Array.prototype.each != 'function'){
        Array.prototype.each = function(callback, context){
            if(this.length > 0 && typeof callback == 'function'){
                for(var i = 0; i < this.length; i++){
                    callback.call(context || window, this[i]);
                }
            }
        }
    }

    var a = [1, 2, 3, 4, 5];

    a.each(function(value){
        alert(value);
        });

You need to login to post a comment.