js中的for循环,具有启动器功能

For loop in js with function for starter

我有工作。不幸的是我被卡住了。你可以帮帮我吗。 项目:

问一句用户分析。 要求查看您希望用户对块进行计数的字母。 计算该字母在句子中出现的次数。 弹出window然后输入下面这句话:"The letter X times Y occurs in this sentence." 必须使用功能! 我这样写:

function bernardTheLetterCounter() {
  var sentence = prompt("Please type in the phrase to be examined");
  var letter = prompt("Please enter the letters were looking for.");

  for (i = 0; i <= sentence.length; i++) {
    if (sentence.charAt(i) == letter) {
      alert("The letter " + letter + " occurs " + sentence.charAt(i) + " times in this sentence.")
    }
  }
  return;
}


bernardTheLetterCounter();

你必须完成计数(循环内部),然后在循环完成后打印结果。像这样:

function bernardTheLetterCounter() {
  var sentence = prompt("Please type in the phrase to be examined");
  var letter = prompt("Please enter the letters were looking for.");

  var count = 0; // the counter (initialized to 0)
  // use var i instead of i (to make i local not global: this is just an advice)
  for (var i = 0; i <= sentence.length; i++) {
    if (sentence.charAt(i) == letter) { // if it is THE LETTER
      count++; // increment the counter (add 1 to counter)
    }
  }
  alert("The letter " + letter + " occurs " + count + " times in this sentence."); // use counter to print the result after the counting is done
  // the return here has no meaning
}


bernardTheLetterCounter();

你所做的是每次找到字母时打印一条消息(这对用户来说很丑陋,尤其是当那个字母的数量很大时)。

本例中的函数可以re-used测试。 (ps。for-loop 不是解决问题的有效方法)。

var sentence = prompt("Please type in the phrase to be examined:");
var letter = prompt("Please enter the letter you are looking for:");

function countLettersInString(source, letterToFind) {
  return source
    .split('')
    .filter(function(letter) { return letter === letterToFind; })
    .length;
}

console.log([
  'letter', letter,
  'was found', countLettersInString(sentence, letter),
  'times.'
].join(' '));