统计各元素出现的次数(字符串,数组)
let str = ['a','b','b','d2','cd','ssd','d','k'];
function arrNum(str){
if(str.length>0){
let strarr
if(str instanceof Array){
strarr = str
}else{
strarr = str.split('')
}
return strarr.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur]=1
}
return pre
},{})
}
console.log(arrNum(str) );
console.log(arrNum(str).d ); //某元素在目标对象里出现的次数
本文来自博客园,作者:喆星高照,转载请注明原文链接:https://www.cnblogs.com/houxianzhou/p/13259494.html