Javascript Array myMap(func)

Description

Javascript Array myMap(func)


Array.prototype.myMap = function(func) {
  var tempArr = [];
  for(var i = 0; i < this.length; i++) {
    tempArr.push(func(this[i]));/*  w  w  w  .j av a2  s  .  c om*/
  }
  return tempArr;
};

var arr = [1,2,3,4,5];
console.log("Original Array: ", arr); // Original Array:  [1, 2, 3, 4, 5]
var newArr = arr.myMap(function(num) { // We can call myMap off the array type now because I extended Array with Array.prototype.myMap above
  return num*2;
});
console.log("New Array ", newArr); // New Array:  [2, 4, 6, 8, 10]

Javascript Array myMap(func)

Array.prototype.myMap = function (func) {
  let ret_arr = [];

  function action(el) {
    ret_arr.push(func(el));//w  ww  .j  a  va  2  s. c  om
  }

  this.myEach(action);

  return ret_arr;
};

// console.log([1,2,3].myMap(el => el + 5));

Javascript Array myMap(func)

//myMap/*ww  w.  ja  va2s  .c om*/
Array.prototype.myMap = function(func) {
  var result = [];

  function addResult(element) {
    result.push(func(element));
  }

  this.myEach(addResult);

  return result;
}



PreviousNext

Related