我正在编写关于功能JS的教程,我需要使用reduce方法来应对挑战:
给定一个随机数组的单词,输出一个显示单词加上单词数的数组,例如:['apple, 'orange, 'grape', 'apple']- >['apple: 2','orange: 1', 'grape: 1]
我知道这不是reduce的正确用法,但这是我的半工作解决方案:
var wordCountsArray = inputWords.map(function(item){
var counter = 0;
var itemCount = inputWords.reduce(function(prevVal, curVal){
if(curVal==item){
counter++;
}
return;
},0);
return item+": "+counter;
})
return wordCountsArray;
}
Run Code Online (Sandbox Code Playgroud)
这确实输出了单词计数,但单词计数列表有重复,即看起来像:
['apple: 2','orange: 1', 'grape: 1, 'apple: 2']
Run Code Online (Sandbox Code Playgroud)
代替
['apple: 2','orange: 1', 'grape: 1]
Run Code Online (Sandbox Code Playgroud)
我查阅了MSDN的方法指南,Mozilla的,几个博客.我得到它作为累加器如何工作,但因为它使用最后一次迭代的输出作为下一个的输入,我不知道如何将它应用于此任务.我不需要解决方案,但在理解方面可能有点帮助?