返回输入中每个字符的递归函数

我正在尝试使用递归来返回字符串中的每个字符。然而,输出不是


//We define a function with input parameter.

function countCharInString(string) {

  //vi Define an empty objec 

  const result = {};

  //we loop through the length of string

  for (let i = 0; i < string.length; i++) { 

    //create another variable for each element in string

    const ch = string[i];

    //BASE CASE: if string is empty, return Object with nothing 

    if (!result[ch]) {

      return result[ch]=0;

    } else {

      //RECURSION: 1 plus whatever the length of the substring from the next character onwards is

      return countCharInString(result[ch] + 1)

    }  

  }

}

console.log(countCharInString("Vi skal tælle bogstaver"))

输出应如下所示:


var result = {

l : 3,

a : 2,

e : 2,

s : 2,

t : 2,

v : 2,

b: 1,

i : 1,

k : 1,

o : 1,

r : 1,

æ : 1

};


偶然的你
浏览 126回答 2
2回答

叮当猫咪

我建议像这样简单地减少var inputString = 'donald duck';var result = inputString.split('').reduce((acc, char, index) => {&nbsp; &nbsp; if (acc[char] !== undefined) {&nbsp; &nbsp; &nbsp; acc[char] = acc[char] + 1;&nbsp; }&nbsp; else {&nbsp; &nbsp; acc = { ...acc, [char]: 1 }&nbsp; }&nbsp; return acc}, {})参见: https:&nbsp;//jsfiddle.net/yswu91zh/21/

饮歌长啸

仅递归不会给您所需的输出。递归计算字符后,您必须按频率排序,然后按字符排序。我已经从计数中排除了一堆带空格的标点符号,如果您想排除更多,只需将其添加到标点符号字符串中即可。你必须使用String.prototype.localeCompare()方法来比较字符。此方法比较当前区域设置中的两个字符串。当您使用丹麦语时,您必须将区域设置指定为da。const punctuations = '.,:;!? ';const countCharInString = (str, p = {}) => {&nbsp; if (str.length === 0) return p;&nbsp; const key = str[0].toLowerCase();&nbsp; if (!punctuations.includes(key)) {&nbsp; &nbsp; if (!p[key]) p[key] = 1;&nbsp; &nbsp; else p[key] += 1;&nbsp; }&nbsp; return countCharInString(str.slice(1), p);};const cmp = (x, y) => {&nbsp; if (x[1] === y[1]) {&nbsp; &nbsp; return x[0].localeCompare(y[0], 'da');&nbsp; }&nbsp; return x[1] < y[1] ? 1 : -1;};const ret = Object.fromEntries(&nbsp; Object.entries(countCharInString('Vi skal tælle bogstaver')).sort(cmp));console.log(ret);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript