相信平时书写代码中一定会遇到需要统计字符出现次数的
普通版
let st = 'daaadahsdahsdgywawahdshahdgahgdadahdgadg'
let aaa = {}
for (let i = 0; i < st.length; i++) {
if (aaa[st[i]]) {
aaa[st[i]]++
} else {
aaa[st[i]] = 1
}
}
console.log(aaa);
结果:{d: 10, a: 12, h: 7, s: 3, g: 5, …}
升级版
let st = 'daaadahsdahsdgywawahdshahdgahgdadahdgadg'
let sum = st.split('').reduce((total, item) => {
if (total[item]) {
total[item]++
} else {
total[item] = 1
}
return total
}, {})
console.log(sum);
最终升级版
let st = 'daaadahsdahsdgywawahdshahdgahgdadahdgadg'
let sum = st.split('').reduce((total, item) => {
total[item]++ || (total[item] = 1)
return total
}, {})
console.log(sum);
total[item]++第一次没有为Nan,Nan在判断力为false