先来看看运行效果截图:
具体代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>求字符串中每个字符出现的次数 </title> <script type="text/javascript"> var str = "abdcadfasfdbadfafdasdfasyweroweurowqrewqrwqrebwqrewqrejwq;;"; var array = str.split(""); array.sort(); var countArray = []; var CountObj = function(character){ this.count = 1 this.character = character; return this; } var arrayObj = null, countArrayObj = null, arrayLength = 0; for (var i = 0, length = array.length; i < length; i++) { arrayObj = array[i]; arrayLength = countArray.length; if (arrayLength > 0) { countArrayObj = countArray[arrayLength - 1]; if (countArrayObj.character == arrayObj) { countArrayObj.count = countArrayObj.count + 1; } else { countArray.push(new CountObj(arrayObj)); } } else { countArray.push(new CountObj(arrayObj)); } } /** * 输出每个字母和其对应出现的统计数据 */ for(var i=0,length=countArray.length; i<length; i++) { countArrayObj = countArray[i]; console.log(countArrayObj.character + ":" + countArrayObj.count); } </script> </head> <body> </body> </html>
更多关于JavaScript算法相关内容感兴趣的读者可查看本站专题:《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数据结构与算法技巧总结》