// 返回数组中每个元素出现的次数
// 参数是任意数组,reduce的第2个参数要传一个空对象,这个空对象就是返回的个数的对象
var getNumCount = function(array) {
return array.reduce((total,currentVal) => {
if(currentVal in total)
{
total[currentVal]++;
}
else
{
total[currentVal] = 1;
}
return total;
},{})
}
console.log(getNumCount([1, 2, 2, 3, 1])) // { '1': 2, '2': 2, '3': 1 }
js中统计数组中元素出现的个数
最新推荐文章于 2024-03-03 21:16:32 发布