Home >Web Front-end >JS Tutorial >jQuery gets the number that appears most in a string_jquery

jQuery gets the number that appears most in a string_jquery

WBOY
WBOYOriginal
2016-05-16 15:14:172004browse

Recommended reading: A tool to count the occurrences of each string in jQuery

No more nonsense, I will just post the js code for you.

//获取字符串中出现最多的数和它一共出现多少次
var str = 'asdfssaaasasasasaa'; //定义字符串
var json = {}; //定义数组用来存储每个字符元素所对应的个数
for (var i = 0; i < str.length; i++) { //遍历字符串中所有的元素
if (!json[str.charAt(i)]) { //判断当前元素是否已经在数组中存在 str.charAt(i)//当前元素
json[str.charAt(i)] = 1; //给对应数组元素中个数赋值
}
else 
{
json[str.charAt(i)]++; //给数组中元素个数赋值
}
};
var iMax = 0;//出现次数
var iIndex = '';//元素名称
for(var i in json){ //重新赋值出现最多的数据和个数
if(json[i]>iMax){
iMax = json[i];
iIndex = i;
}
}
//alert('出现次数最多的是:'+iIndex+'出现'+iMax+'次');

The above code is the jQuery introduced by the editor to get the most frequent numbers in a string. The code is simple and easy to understand. If you don’t understand anything, please leave me a message and I will get in touch with you in time.

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