首页 > 代码库 > 统计字符串中每个字符的个数

统计字符串中每个字符的个数

技术分享
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>统计字符串中每个字符的个数@</title>
 6 </head>
 7 <body>
 8 </body>
 9 
10 <script type="text/javascript">
11     function f(str) {
12 
13         var arr = str.split("");
14 
15         var obj = {};
16 
17         for (var i = 0; i < arr.length; i++) {
18 
19             var val = arr[i];    //每个数组元素用val变量接收
20 
21             if (obj[val] && obj[val].value =http://www.mamicode.com/= val) {"acaddkkk";
51 
52     f(s);
53 
54 
55 </script>
56 
57 </html>
View Code
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>统计字符串中每个字符的个数@</title>
</head>
<body>
</body>

<script type="text/javascript">
function f(str) {

var arr = str.split("");

var obj = {};

for (var i = 0; i < arr.length; i++) {

var val = arr[i]; //每个数组元素用val变量接收

if (obj[val] && obj[val].value =http://www.mamicode.com/= val) {
//如果obj[val]对象存在并且obj[val]对象的value值为val

obj[val].count+=1;

} else {

obj[val] = {}; //创建obj[val]这个对象


obj[val].value = http://www.mamicode.com/val; //obj[val]对象的value值为val


obj[val].count = 1; //obj[val]对象的count值为1


}

}

for (var key in obj) { //创建对象后循环遍历

console.log(obj[key].value + ‘=‘ + obj[key].count); //控制台输出值

}

}

// 运行代码:
var s = "acaddkkk";

f(s);


</script>

</html>

统计字符串中每个字符的个数