// 计算数组中每个元素出现的次数
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
封装成数组的一个方法
Array.prototype.countTimes = function(){
return this.reduce(function(time,name){
if(name in obj){
obj[name]++;
}else{
obj[name] = 1;
}
return obj;
},{});
}
文章展示了如何使用JavaScript的reduce方法来计算数组中每个元素出现的次数,并将此功能封装为数组的一个新方法countTimes。

被折叠的 条评论
为什么被折叠?



