javascript - reduce统计个数问题

查看:112
本文介绍了javascript - reduce统计个数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在nodeschool上看到这个问题

function countWords(arr) {
  return arr.reduce(function(countMap, word) {
    countMap[word] = ++countMap[word] || 1 // increment or initialize to 1
    return countMap
  }, {}) // second argument to reduce initialises countMap to {}
}

module.exports = countWords

传入数据

var inputWords = ['Apple', 'Banana', 'Apple', 'Durian', 'Durian', 'Durian']

得到的结果

{
    //   Apple: 2,
    //   Banana: 1,
    //   Durian: 3
    // }

实现这个过程的js原理是什么

解决方案

function countWords(arr) {
  // 首先你得知道 reduce 各个参数是啥,可参考 MDN。
  return arr.reduce(function(countMap, word) {
    // countMap 一直在过程中传递
    // 如果 countMap[word] 存在,则 countMap[word] = ++countMap[word] = countMap[word] + 1,即加一
    // 如果 countMap[word] 不存在,则 countMap[word] = ++undefined || 1 = NaN || 1 = 1,即初始化为一
    countMap[word] = ++countMap[word] || 1
    return countMap
  }, {}) // {} 就是 countMap,初始化为空对象
}

这篇关于javascript - reduce统计个数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆