Javascript Array map(fn)

Description

Javascript Array map(fn)


Array.prototype.map = function(fn) {
  let temp = []// ww  w . j a v  a2s  . c  o m
  temp.push(fn(this[0], 0, this))
  this.reduce((preValue, value, index, array) => {
    temp.push(fn(value, index, array))
    return value
  })
  return temp
}

Javascript Array map(fn)

Array.prototype.map = function (fn) {
  let ret = [];//from w  w w  . j  a v a2 s.  c om
  this.reduce((prev, cur) => {
    ret.push(fn.call(null, cur));
    return cur;
  }, null);
  return ret;
}

let con = [1, 2, 3];

console.log(con.map(item => item * 2));

Javascript Array map(fn)

var _;/*from  w  w w .  j a va2  s .  com*/

_ = require('lodash');

Array.prototype.map = function(fn) {
  return _.map(this, fn);
};

Array.prototype.mapBang = function(fn) {
  var idx;
  idx = 0;
  return _.map(this, (function(_this) {
    return function(element) {
      _this[idx] = fn(element);
      return idx++;
    };
  })(this));
};

Array.prototype.toSentence = function() {
  return this.slice(0, this.length - 1).join(', ') + " and " + this.slice(-1);
};

Array.tryConvert = function(obj) {
  if (obj instanceof Array) {
    return obj;
  } else {
    return null;
  }
};

Javascript Array map(fn)

Array.prototype.map = function (fn) {
 var ret = [];//from w  w w.  java  2  s . co  m
 for (var i=0; i<this.length; i++)
  ret.push( fn(this[i]) );
 return ret;
};



PreviousNext

Related