使用 JavaScript 计算字符串中每个字符的出现次数?
javascriptweb developmentobject oriented programming
使用一个数组来存储每个字符的频率。如果找到相似的字符,则加一,否则将 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