Какова логическая ошибка в этом коде подсчета символов? - PullRequest
0 голосов
/ 10 ноября 2019

Я действительно стою на месте, почему это не работает, как задумано. Он должен вывести число 4 для количества вхождений буквы s в слове Mississipi. Я новичок в 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"));

Ответы [ 3 ]

1 голос
/ 10 ноября 2019

Вам не нужно Array.indexOf(), чтобы найти текущего персонажа. Поскольку i является индексом текущего символа, используйте его, чтобы взять текущий символ из строки и сравнить с целью. Верните count в конце.

Примечание: оператор return в JS не может вернуть два элемента. Если вы используете разделенный запятыми список - например, 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"));
0 голосов
/ 10 ноября 2019

Здесь вы делаете сравнение с индексом и целью. Вы должны получить текущий символ, а затем сравнить. как я сделал ниже, это может помочь вам ...

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"));
0 голосов
/ 10 ноября 2019

Вот в чем дело: вы пытаетесь получить доступ к письму через 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"));
...