Posted in Javascript onJanuary 28, 2016
本文实例讲述了JavaScript统计字符串中每个字符出现次数的方法。分享给大家供大家参考,具体如下:
这是一个面试题,要求随便给你一个字符串,让你求出字符串中每个字符出现的次数。
先来看看运行效果截图:
具体代码如下:
<!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统计字符串中每个字符出现次数完整实例
- Author -
m1870164声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@