for js with starter for starter

时间:2017-02-07 11:01:59

标签: javascript for-loop alert

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

询问用户分析的句子。 询问您希望用户使用哪些字母来计算块。 计算字母在句子中出现的次数。 弹出窗口然后键入以下句子:"在该句中出现字母X乘Y." 必须使用功能! 我写这个:



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();
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

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

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();

你所做的就是每次找到信件时都会打印一条信息(这对用户来说很难看,特别是如果这封信的数量很大)。

答案 1 :(得分:0)

此示例中的功能可以重复使用和测试。 (ps。for-loop不是解决问题的有效方法)。

&#13;
&#13;
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(' '));
&#13;
&#13;
&#13;