题目如下 统计一串字符串中每个字符出现的频率
示例字符串
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
小白写法
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
let result = {};
for (let i = 0; i < str.length; i++) {
if (result[str[i]]) {
result[str[i]]++;
}
else {
result[str[i]] = 1;
}
}
console.log(result);
但是这种写法明显丑陋不堪,代码量太多了,一点也不像卷狗写的代码
我们可以试着改进一下,使用数组的foreach
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
let result = {};
str.split('').forEach(function (item) {
if (result[item]) {
result[item]++
} else {
result[item] = 1
}
});
console.log(result);
如上,虽然这样也能写出来发,但是这种代码都看能得懂,一点也不酷,作为卷狗,就是得写的别人看不懂
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
let result = {};
// 使用reduce统计字符串中每个字符出现的次数
str.split('').reduce((pre, cur) => {
if (pre[cur]) {
pre[cur]++;
} else {
pre[cur] = 1;
}
return pre;
}, result);
console.log(result);
如上,reduce这个用的人比较少,应该能让一部分看不懂但是还是有风险
所以再加上es6的语法保险一些
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
let result = {};
str.split('').reduce((pre, cur) =>(pre[cur]++ || (pre[cur] = 1), pre), result);
console.log(result);
不对不对,我都用es6写法了,我还整啥对象?我用map啊,哇,还是一行了耶,性能更好了,看起来更酷了呢
let str = 'asdfasqwerqwrdfafafasdfopasdfopckpasdfassfd'
let result = str.split('').reduce((pre, cur) =>pre.set(cur, (pre.get(cur) || 0) + 1), new Map())
console.log(result)
没别的意思,只是想卷死在座的各位,或者被在坐的各位卷死,有没有比我还要卷的
耗时5.133ms