写下划线_.使用_.each减少方法

writing underscore _.reduce method using _.each

本文关键字:方法 使用 下划线 each      更新时间:2023-09-26

我正在练习在下划线库中重写reduce方法。

我想这样做,如果没有传递起始值,第一个元素被用作累加器,并且永远不会传递给迭代器。

我已经把它写在下面了。我不知道怎样才能让第一个元素不传递给迭代器。欢迎指教。

  _.reduce = function(collection, iterator, accumulator) {
    if(arguments.length == 2) accumulator = collection[0];
    _.each(collection, function(el){
      accumulator = iterator(accumulator, el);
    })
    return accumulator;
  };

这就是_.first_.rest派上用场的地方:

_.reduce = function (collection, iterator, accumulator) {
    if (arguments.length == 2) {
        accumulator = _.first(collection);
        collection = _.rest(collection);
    }
    _.each(collection, function (el) {
        accumulator = iterator(accumulator, el);
    })
    return accumulator;
};