javascript - reduce统计个数问题
怪我咯
怪我咯 2017-04-10 18:00:58
[JavaScript讨论组]

在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原理是什么

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
阿神
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,初始化为空对象
}
阿神

首先知道 reduce 函数的作用:Array.prototype.reduce() - JavaScript | MDN

开断点跟一下就明白了:

countMap 初始值为 {}

第一轮:

{
    Apple: 1
}

第二轮:

{
    Apple:1,
    Banana:1
}

第三轮:

{
    Apple:2,
    Banana:1
}

以此类推。。。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号