猿问

这个字符计数代码的逻辑错误是什么?

对于为什么这不能按预期工作,我真的处于停滞状态。它应该输出字母 s 在单词 Mississipi 中出现次数的数字 4。我是 javascript 新手,所以任何帮助将不胜感激。利亚姆


function countCharacters(target, input) { //Defining of the function, the parameters are target and input

  var count = 0; //set count to 0 before the for loop

  for (var i = 0; i < input.length; i = i + 1) { //the for loop that goes through each index of the input string

    if (input.indexOf(i) == target) { //if a character in the string matches the target character

      count = count + 1; //count adds 1 to its value

    }

  }

  console.log(count); //When it breaks out of the loop, the amount of times the target was matched will be printed

  return target, input; //return two parameters

}


console.log(countCharacters("s", "Mississippi"));


胡子哥哥
浏览 141回答 3
3回答

红糖糍粑

您不需要Array.indexOf()找到当前角色。由于i是当前字符的索引,用它从字符串中取出当前字符,并与目标进行比较。最后返回count。注意:returnJS 中的语句不能返回两个项。如果您使用逗号分隔的列表 -target, input例如 - 最后一项将被返回。function countCharacters(target, input) {&nbsp; var count = 0;&nbsp;&nbsp;&nbsp; for (var i = 0; i < input.length; i = i + 1) {&nbsp; &nbsp; if (input[i] === target) { //if a character in the string matches the target character&nbsp; &nbsp; &nbsp; count = count + 1;&nbsp; &nbsp; }&nbsp; }&nbsp; return count;}console.log(countCharacters("s", "Mississippi"));

慕斯王

在这里,您正在与索引和目标进行比较。你应该得到当前字符然后比较。正如我在下面所做的那样,它可能会帮助您...function countCharacters(target, input) { //Defining of the function, the parameters are target and input&nbsp; var count = 0; //set count to 0 before the for loop&nbsp; for (var i = 0; i < input.length; i = i + 1) { //the for loop that goes through each index of the input string&nbsp; &nbsp; if (input[i] == target) { //if a character in the string matches the target character&nbsp; &nbsp; &nbsp; count = count + 1; //count adds 1 to its value&nbsp; &nbsp; }&nbsp; }&nbsp; console.log(count); //When it breaks out of the loop, the amount of times the target was matched will be printed&nbsp; return target, input; //return two parameters}console.log(countCharacters("s", "Mississippi"));

慕标琳琳

事情是这样的:您尝试通过 indexOf() 访问字母 - 最好通过索引访问它,而且函数必须只返回一件事,而您的则返回两件事function countCharacters(target, input) {&nbsp;&nbsp; let count = 0;&nbsp;&nbsp; for (let i = 0; i < input.length; i++) {&nbsp;&nbsp; &nbsp; if (input[i] === target) {&nbsp;&nbsp; &nbsp; &nbsp; count++;&nbsp;&nbsp; &nbsp; }&nbsp; }&nbsp;&nbsp; return count;}console.log(countCharacters("s", "Mississippi"));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答