在javascript中解构reduce函数

时间:2015-03-30 16:30:57

标签: javascript arrays for-loop

使用常规的内置reduce函数,如果不指定初始起始值,它将开始包装前2个数组值。有没有办法用forEach代替我现在的forLoop?我尝试使用forEach,但我不知道如何从arr [1]开始。如果我像第二个条件那样使用forEach,它会给我11而不是10。

function reduce(arr, callback, start) {
  if (start === undefined) {
    var current = arr[0];
    for (var i = 1; i < arr.length; i++) {
      current = callback(current, arr[i]);
    }
    return current;
  }
  else {
    var current = start;
    arr.forEach(function(e) {
      current = callback(current, e);
    });
    return current;
  }
}

console.log(reduce([1, 2, 3, 4], function(a, b) {
  return a + b;
}));  //-> should return 10

1 个答案:

答案 0 :(得分:0)

找到this polyfill以将reduce添加到不支持它的浏览器。

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
if (!Array.prototype.reduce) {
  Array.prototype.reduce = function(callback /*, initialValue*/) {
    'use strict';
    if (this == null) {
      throw new TypeError('Array.prototype.reduce called on null or undefined');
    }
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    var t = Object(this), len = t.length >>> 0, k = 0, value;
    if (arguments.length == 2) {
      value = arguments[1];
    } else {
      while (k < len && !(k in t)) {
        k++; 
      }
      if (k >= len) {
        throw new TypeError('Reduce of empty array with no initial value');
      }
      value = t[k++];
    }
    for (; k < len; k++) {
      if (k in t) {
        value = callback(value, t[k], k, t);
      }
    }
    return value;
  };
}