编写一个名为strLetterCount的函数,该函数接受一个字符串,并返回一个包含每个字母及其在字符串中的计数的新字符串

问题描述 投票:2回答:1

编写一个名为strLetterCount的函数,该函数接受一个字符串,并返回一个新字符串,每个字符后跟出现在字符串中的次数。字符应按与字符串相同的顺序返回,每个字母均带有唯一字母,后跟出现在字符串中的次数。

到目前为止,我的代码是:

//write function format with argument
    function strLetterCount (str){
      //initialize var to hold results for charAt
      let charAt = '';
      let count = 0;
      for(let i = 0; i < str.length; i++){
        str.charAt(i);
        results = str.charAt(i);
        for (let j = 0; j < str.length ; j++){
          if(str[i] === str){
            count++
            results = str.charAt(i) + count++
          }
        }
        return results;
      }
    }

    strLetterCount('taco'); //'t1a1c1o1'

    //function should pass a string as argument
    //loop through the string and if a new char is entered store that 
    //loop through string again and count num of new char
    //returns a new string push charAt and numOfOcc

它应该返回't1a1c101'的输出,但是,我只让它在字符串中循环一次并返回't'的第一个值,但是它不计算出现的次数吗?我无法确定在哪里更改逻辑以保存发生次数?

javascript helper question-answering javahelp
1个回答
0
投票

我想您尝试实现这样的目标。

每个字母将出现在输出字符串中,与输入字符串中出现的次数相同。我不确定这不是您想要的,但这就是strLetterCount函数要执行的操作。

function strLetterCount (str){
   let results = ""

   //initialize var to hold results for charAt
   for(let i = 0; i < str.length; i++)
   {
      // Get current char and store it into the results
      // We will add the count in a second loop
      let charAt = str.charAt(i)
      let count = 0

      results += charAt

      for (let j = 0; j < str.length ; j++)
      {
         if(str.charAt(j) === charAt)
         {
            count++
         }
      }

      results += count
   }

   return results;
}

© www.soinside.com 2019 - 2024. All rights reserved.