使用 JavaScript 统计字符串中每个字符出现的次数?
创建一个数组来存储每个字符的出现频率。如果发现了类似的字符,则将其加一,否则在该数组中放入 1。
假设这是我们的字符串 −
var sentence = "My name is John Smith";
以下是用 JavaScript 统计出现次数的代码 −
范例
var sentence = "My name is John Smith"; sentence=sentence.toLowerCase(); var noOfCountsOfEachCharacter = {}; var getCharacter, counter, actualLength, noOfCount; for (counter = 0, actualLength = sentence.length; counter < actualLength; ++counter) { getCharacter = sentence.charAt(counter); noOfCount = noOfCountsOfEachCharacter[getCharacter]; noOfCountsOfEachCharacter[getCharacter] = noOfCount ? noOfCount + 1: 1; } for (getCharacter in noOfCountsOfEachCharacter) { if(getCharacter!=' ') console.log("Character="+getCharacter + " Occurrences=" + noOfCountsOfEachCharacter[getCharacter]); }
要运行上述程序,需要使用以下命令 −
node fileName.js.
这里,我的文件名是 demo40.js。
输出
这将产生以下输出 −
PS C:\Users\Amit\JavaScript-code> node demo40.js Character=m Occurrences=3 Character=y Occurrences=1 Character=n Occurrences=2 Character=a Occurrences=1 Character=e Occurrences=1 Character=i Occurrences=2 Character=s Occurrences=2 Character=j Occurrences=1 Character=o Occurrences=1 Character=h Occurrences=2 Character=t Occurrences=1
广告