使用Javascript

时间:2017-07-20 04:01:11

标签: javascript function

我遇到过一个关于使用HTML中的表单计算句子的问题,但我想先找出函数,看看它是否有效。这是我的功能,我无法让它在jsfiddle(https://jsfiddle.net/jdloomis/fxt81ynu/2/)中运行:

var numSentences = 0;

function calSentences(longString) {
  var length = longString.length;
  var sentence = '';

for (var i = 0; i < length; i++) {
  sentence += longString[i];

  if (longString[i] == '.') {
    numSentences++;
    sentence = '';
    }
  }
}

console.log(calSentences("This is a sentence. My second sentence."));

我已经能够找出大部分功能以及他们在我的书中做了什么,除了这个和没有使用.split的单词计数,如果我无法弄明白,我会在另一篇文章中发布那个。

2 个答案:

答案 0 :(得分:0)

如此关闭你的尝试!您忘记做的只是返回 return numSentences的句子数量

&#13;
&#13;
var numSentences = 0;

function calSentences(longString) {
  var length = longString.length;
  var sentence = '';

  for (var i = 0; i < length; i++) {
    sentence += longString[i];
    if (longString[i] == '.') {
      numSentences++;
      sentence = '';
    }
  }

  return numSentences;
}

console.log(calSentences("This is a sentence. My second sentence."));
&#13;
&#13;
&#13;

希望这有帮助! :)

答案 1 :(得分:0)

您的代码是正确的,但您没有从函数中返回任何内容。

此外,请将var numSentences保留在您的函数本地,以便每次运行函数时它都会重置为0。否则,每次运行该函数时都会添加到先前的计算中。

function calSentences(longString) {
  var numSentences = 0;
  var length = longString.length;
  var sentence = '';

for (var i = 0; i < length; i++) {
  sentence += longString[i];

  if (longString[i] == '.') {
    numSentences++;
    sentence = '';
    }
  }
  return numSentences;
}

console.log(calSentences("This is a sentence. My second sentence."));