javascript 如何计算数组中单词的字符数?

8oomwypt  于 2022-12-02  发布在  Java
关注(0)|答案(3)|浏览(170)

我有一个数组["academy"],我需要计算数组中字符串的字符数。
输出:

a:2
c:1
d:1
e:1
m:1
y:1

就像这样
我尝试了两个for循环

function sumChar(arr){
    let alph="abcdefghijklmnopqrstuvxyz";
    let count=0;
    for (const iterator of arr) {
        for(let i=0; i<alph.length; i++){
            if(iterator.charAt(i)==alph[i]){
                count++;
                console.log(`${iterator[i]} : ${count}`);
                count=0;
            }
        }
    }
}
console.log(sumChar(["abdulloh"]));

它工作不正常
输出量:

a : 1
b : 1
h : 1
undefined
xmq68pz9

xmq68pz91#

要计算字符串中每个字符出现的次数,可以使用for循环遍历字符串,并将每个字符作为键添加到对象中,值为它出现的次数。下面是一个示例:

// create an empty object to store the character counts
var charCounts = {};

// get the string from the array
var str = ["academy"][0];

// iterate through the string and count the occurrences of each character
for (var i = 0; i < str.length; i++) {
  var char = str[i];
  if (charCounts[char] === undefined) {
    // if the character has not been encountered before, set its count to 1
    charCounts[char] = 1;
  } else {
    // if the character has been encountered before, increment its count by 1
    charCounts[char]++;
  }
}

// print the character counts
for (var char in charCounts) {
  console.log(char + ": " + charCounts[char]);
}
8cdiaqws

8cdiaqws2#

这里有一个简洁的方法。[...new Set(word.split(''))]创建一个字母数组,忽略所有重复的字母。.map从该数组中取出每个字母,并通过长度检查器对其进行检查。({ [m]: word.split(m).length - 1 })将该字母设置为object keyword.split(m).length - 1是一种快速确定该字母出现次数的方法。

const countLetters = word => (
  [...new Set(word.split(''))].map(m => ({
    [m]: word.split(m).length - 1
  })))

console.log(countLetters("academy"))
62lalag4

62lalag43#

你也可以用正则表达式来检查出现的字符串。在这里我做了一个方法来检查字符串中的字符。希望它能有所帮助。

word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
    for(var i = 0;i < this.word.length; i++){
        if(this.charsArrayWithCount[this.word[i]] === undefined){
            this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
        }
    }
    console.log(this.charsArrayWithCount);
}
charCount(string, char) {
    let expression = new RegExp(char, "g");
    return string.match(expression).length;
}

相关问题