Javascript Array reduce(callback, initial)

Description

Javascript Array reduce(callback, initial)


Array.prototype.reduce = function(callback, initial){
  initial = initial || 0;//ww w . j a v  a  2 s.c om
  for (var i=0; i< this.length; i++) {
    initial = callback(initial, this[i], i, this);
  }
  return  initial;
}

//wat = new Array(1,2,3,4);
wat = [1,2, 3, 4]

console.log(wat);
console.log(wat.reduce( (p, c) => p + c));

Javascript Array reduce(callback, initial)

Array.prototype.reduce = function(callback, initial) {
    var t = Object(this), len = t.length >>> 0, k = 0, value;
    if (arguments.length == 2) {
      value = arguments[1];//  w  w w .j  a v a2s . c o  m
    }
    else {
      while (k < len && ! k in t) {
        k++;
      }

      value = t[k++];
    }
    for (; k < len; k++) {
      if (k in t) {
        value = callback(value, t[k], k, t);
      }
    }
    return value;
};



PreviousNext

Related