关于javascript:lodash中reduce函数的实现

5次阅读

共计 522 个字符,预计需要花费 2 分钟才能阅读完成。

function reduceMe(array, iteratee, accumulator, isFirst) {
  // 设置一个初始的下标,设置为 -1
  let index = -1;

  // 设置 length,当数组存在时,length 为数组的长度,否则为 0
  const length = array === null ? 0 : array.length;

  // 当 isFirst 为 true 同时 length != 0 时,accumulator 为数组的第一个元素
  if (isFirst && length) {accumulator = array[++index];
  }

  // 遍历数组 index 小于 length
  while (++index < length) {
    // 调用 iteratee 函数进行数据处理,// iteratee 函数参数:accumulator:起始值,array[index] 为以后数组值,index 为以后数组下标,残缺数组
    // 最初,将 iteratee 返回的值赋值给 accumulator,以提供给下一次 iteratee 函数应用
    accumulator = iteratee(accumulator, array[index], index, array);
  }

  // 返回最初的后果
  return accumulator;
}
正文完
 0