js实现统计字符出现的次数并去重的方法
来源:动视网
责编:小采
时间:2020-11-03 12:31:31
js实现统计字符出现的次数并去重的方法
js实现统计字符出现的次数并去重的方法:代码示例:var str = "aabbccehgfhaasdhgfashdfhabcasd"; // 使结果显示为一个对象,如:{a:2, b:1, c:2, d:1} var obj = {}; // console.log(obj[ "a" ]) // undefined // obj[ &qu
导读js实现统计字符出现的次数并去重的方法:代码示例:var str = "aabbccehgfhaasdhgfashdfhabcasd"; // 使结果显示为一个对象,如:{a:2, b:1, c:2, d:1} var obj = {}; // console.log(obj[ "a" ]) // undefined // obj[ &qu

代码示例:
var str = "aabbccehgfhaasdhgfashdfhabcasd";
// 使结果显示为一个对象,如:{a:2, b:1, c:2, d:1}
var obj = {};
// console.log(obj[ "a" ]) // undefined
// obj[ "a" ] = 1
// obj[ "a" ] ++
// obj[ "b" ] = 1
// obj[ "b" ] ++
// obj[ "b" ] ++
// obj[ "b" ] ++
// obj[ "c" ] = 1
for(var i=0;i<str.length;i++){
// obj[ str[i] ]
if(obj[ str[i] ]){
obj[ str[i] ]++;
}else{
obj[ str[i] ] = 1;
}
}
console.log(obj);
var newStr = "";
for(var key in obj){
newStr += key;
}
console.log(newStr);
推荐教程:js入门教程
js实现统计字符出现的次数并去重的方法
js实现统计字符出现的次数并去重的方法:代码示例:var str = "aabbccehgfhaasdhgfashdfhabcasd"; // 使结果显示为一个对象,如:{a:2, b:1, c:2, d:1} var obj = {}; // console.log(obj[ "a" ]) // undefined // obj[ &qu