Javascript Array sum(selector)

Description

Javascript Array sum(selector)



var test = [5,5,4]

Array.prototype.sum = function(selector) {
    if (typeof selector !== 'function') {
        selector = function(item) {
            return item;
        }/*from w  w w .  ja va2s.c  o  m*/
    }
    var sum = 0;
    for (var i = 0; i < this.length; i++) {
        sum += selector(this[i]);
    }
    return sum;
};


test.sum()

Javascript Array sum(selector)

Array.prototype.sum = function(selector) {
  if (typeof selector !== 'function') {
    selector = function(item) {
      return item;
    };/*from   w  w  w  .  jav a 2  s.  c o m*/
  }
  var sum = 0;
  for (var i = 0; i < this.length; i++) {
    sum += selector(this[i]);
  }
  return sum;
};



PreviousNext

Related