在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原理是什么
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先知道
reduce函数的作用:Array.prototype.reduce() - JavaScript | MDN开断点跟一下就明白了:
countMap初始值为{}第一轮:
第二轮:
第三轮:
以此类推。。。