Javascript Array myForEach(func)

Description

Javascript Array myForEach(func)


// =========/*w  w  w .j  a  v  a  2 s .  com*/
// VERSION 1
// =========
function myForEach(arr, func){
 for (var i = 0; i < arr.length; i++) {
  func(arr[i]);
 }
}

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
myForEach(colors, function(color){
 console.log(color);
});

// =========
// VERSION 2 
// =========
Array.prototype.myForEach = function(func){
  for(var i = 0; i < this.length; i++) {
   func(this[i]);
  }
};

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
colors.myForEach(function(color){
 console.log(color);
});

Javascript Array myForEach(func)

function myForEach(arr, func){
  // loop through array
  for(var i = 0; i < arr.length; i++){
    // call func for each item in array
    func(arr[i]);// ww  w.j av  a  2 s  . co m
  }
}

Array.prototype.myForEach = function(func){
  // loop through array
  for(var i = 0; i < this.length; i++){
    // call func for each item in array
    func(this[i]);
  }
};


// Test functions
function testMyFunc(a){
  console.log('boom ' + a);
}
arr = [1, 'noodles', 'cake'];
myForEach(arr, testMyFunc);
myForEach(arr, function(a){
  console.log('you are a snake, ' + a);
})

arr.myForEach(testMyFunc);
arr.myForEach(function(a){
  console.log('you suck, ' + a);
})

Javascript Array myForEach(func)

// =========//from  w  w  w. j av  a  2 s  .  co  m
// VERSION 1
// =========
function myForEach(arr, func){
 for (var i = 0; i < arr.length; i++) {
  func(arr[i]);
 }
}
var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
myForEach(colors, function(color){
 console.log(color);
});

// =========
// VERSION 2 
// =========
Array.prototype.myForEach = function(func){
  for(var i = 0; i < this.length; i++) {
   func(this[i])
  }
}

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
colors.forEach(function(color){
 console.log(color);
});

Javascript Array myForEach(func)

// =========/*  w  ww  .  j  a v a2s. c  o  m*/
// VERSION 2 
// =========
Array.prototype.myForEach = function(func){
  for(var i = 0; i < this.length; i++) {
   func(this[i])
  }
}

var colors = ["red", "orange", "yellow", "green", "blue", "PURPLE"];
colors.forEach(function(color){
 console.log(color);
});



PreviousNext

Related