js记录重复字母的个数

时间:2022-04-17 21:03:52

var str = "hello";
var obj = {};
for (var i = 0; i < str.length; i++) {
var v = str.charAt(i); //获得每个字符
if (obj[v] && obj[v].value == v) { //筛选
obj[v].count = ++obj[v].count; //记录每个重复的字符个数
} else {
obj[v] = {};
obj[v].count = 1;
obj[v].value = v;
}
}
for (key in obj) {
document.write(obj[key].value + '=' + obj[key].count + ',');
}