此字符计数代码中的逻辑错误是什么?

我真的停滞不前,为什么这不能按预期进行。它应输出密西西比词中字母s的出现次数的数字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"));

zudy2 回答:此字符计数代码中的逻辑错误是什么?

您不需要Array.indexOf()来查找当前字符。由于i是当前字符的索引,因此可以使用它从字符串中获取当前字符,并与目标进行比较。最后返回count

注意:JS中的return语句不能返回两个项目。如果您使用逗号分隔的列表-例如target,input-将返回最后一项。

function countCharacters(target,input) {
  var count = 0;
  
  for (var i = 0; i < input.length; i = i + 1) {
    if (input[i] === target) { //if a character in the string matches the target character
      count = count + 1;
    }
  }

  return count;
}

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

,

这是问题:您尝试通过indexOf()访问字母-更好地通过索引访问它,函数也必须只返回一件事,而您的返回两个

function countCharacters(target,input) { 
  let count = 0; 
  for (let i = 0; i < input.length; i++) { 
    if (input[i] === target) { 
      count++; 
    }
  } 
  return count;
}

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

这里您正在与索引和目标进行比较。您应该获取当前字符然后进行比较。就像我在下面所做的那样,它可能会帮助您...

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[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"));

本文链接:https://www.f2er.com/3127826.html

大家都在问