JS counts the number of occurrences of letters in a string
1. Realize the number of occurrences of each letter in a JS statistical string in a conventional way
//创建一个空对象,目的:把字母作为键,次数作为值
function countStr(str) {
var obj = {
};//创建一个空对象
for (var i = 0; i < str.length; i++) {
//遍历字符串,获得每个字母
var key = str[i];//每个字母
if (obj[key]) {
obj[key]++;//判断obj中有没有这个键
} else {
//对象中没有这个字母,那就把字母加到对象中,并且给这个字母一个出现的次数,默认一次
obj[key] = 1;//此时会把每个字母变成属性,并赋予属性值1
}
}
//遍历对象,显示每个字母的次数
for (var key in obj) {
console.log(key + "出现了" + obj[key] + "次");
}
}
Effect:
Two, one line of code realizes the number of occurrences of each letter in the JS statistical string
function countStr(str){
return [...str].reduce((a,b)=>(a[b]?a[b]++:a[b]=1,a),{
});
}
This method is more convenient, and the returned result is an Object object:
3. Summary
If we don’t want the code we worked so hard to be plagiarized by others, we can take some measures, such as code obfuscation and encryption . Recently, we found a free and easy-to-use online tool with a simple interface and no ads: jsjiami.cn , share it with everyone Experience the experience.