「跟着渡一学前端」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。

浙公网安备 33010602011771号