Home >Web Front-end >JS Tutorial >Complete example of JavaScript counting the number of occurrences of each character in a string_javascript skills
The example in this article describes how JavaScript counts the number of occurrences of each character in a string. Share it with everyone for your reference, the details are as follows:
This is an interview question. You are asked to give you a random string and ask you to find the number of occurrences of each character in the string.
Let’s take a look at the screenshots of the running effect:
The specific code is as follows:
<!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>
Readers who are interested in more content related to JavaScript algorithms can check out the special topics on this site: "Summary of JavaScript sorting algorithms", "Summary of JavaScript traversal algorithms and techniques" and "Summary of JavaScript data structure and algorithm skills》
I hope this article will be helpful to everyone in JavaScript programming.