Loading

「跟着渡一学前端」Lodash——手写countBy函数

学习资源

完整代码

function countBy(collection, iteratee) {
  const result = {};
  for (const item of collection) {
    const key = iteratee(item);
    result[key] ? result[key]++ : (result[key] = 1);
  }
  return result;
}

代码详解

  • 参数了解——collection 集合,iteratee迭代函数用于生成键。
  • 考虑如何遍历集合:因为collection可能为数组也可能为对象——所以使用for-of遍历。
  • 考虑键名生成——使用迭代函数生成键。
  • 进行遍历统计——若有值则累加,若无值则初始化为1。
posted @ 2025-02-18 22:54  lao-jiawei  阅读(42)  评论(0)    收藏  举报