用js怎么来检测字符串中每个字符出现的次数

it2023-03-05  74

我的网站:点此进入

前端QQ交流群:1063233592

 

var text = 'abcdabdefrhgsj'; // 查看一个字符串中各个字符出现的次数 function charCount(str) { var json = {}; for(var i = 0;i<str.length;i++){ if(json[str[i]]){ json[str[i]]++ }else{ json[str[i]] = 1; } } return json; } console.log(charCount(text)) /* { a: 2 b: 2 c: 1 d: 2 e: 1 f: 1 r: 1 h: 1 g: 1 s: 1 j: 1 } */

 

最新回复(0)