Home  >  Article  >  Web Front-end  >  How to count the number of occurrences of each character in a string using js?

How to count the number of occurrences of each character in a string using js?

coldplay.xixi
coldplay.xixiOriginal
2020-06-20 15:55:1512674browse

How to count the number of occurrences of each character in a string using js?

How to use js to count the number of occurrences of each character in a string?

JS method of counting the number of occurrences of each character in a string:

<script>
 
/*这个字符串中的每个字每出现了多少次*/
var ary = "asasDFGHadDfFFhjkMNJGBHGDsdfghjfghjkdfghjkl";
var obj = {};
var i = 0;
 
ary1 = ary.toLocaleLowerCase(); //将字符串转为小写
 
for(i = 0; i < ary1.length; i++)
{
key = ary1[i];
 
if(obj[key])
{
//对象中有这个字母
obj[key]++;
}
else
{
//对象中没有这个字母,把字母加到对象中
obj[key] = 1;
}
}
 
for(var key in obj) //遍历这个对象
{
console.log(key + "这个字母出现了" + obj[key] + "次");
}
</script>

Running results:

How to count the number of occurrences of each character in a string using js?

Recommended tutorial: "javascript basic tutorial"

The above is the detailed content of How to count the number of occurrences of each character in a string using js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn