我函数中的逻辑错误导致count ++无法正常工作

时间:2018-11-03 11:26:04

标签: javascript function count

我正在努力寻找此代码中的最后一个逻辑错误,它仍然返回Found 0的愿望,而不是12。

var msg = 'I wish to wish the WISH you wish to wish but if you wish '
+ 'the WISH the witches wish I won\'t wish the WISH you wish '
+ 'to wish';
document.writeln('Found ' + countTerms(msg) + ' wishes.');
function countTerms(phrase) {
var i = 1;
var count = 0 ;
var terms = phrase.split(' ');
    for (i = 0; i < terms.length - 1; i++){
        if (terms[i].toUpperCase() == 'WISH'){
return count++;
        }
    }
}

5 个答案:

答案 0 :(得分:0)

在循环中的return中,对于第一个匹配项,我们将返回count,然后递增,这意味着函数本身将在其中返回0。如果没有这样的匹配,它将返回undefined(默认返回)。

您将需要在for循环之后返回count。另外,for循环中的条件必须为i < terms.length,否则,我们将错过数组中的最后一个值。

var msg = 'I wish to wish the WISH you wish to wish but if you wish '
+ 'the WISH the witches wish I won\'t wish the WISH you wish '
+ 'to wish';
document.writeln('Found ' + countTerms(msg) + ' wishes.');
function countTerms(phrase) {
  var i = 1;
  var count = 0 ;
  var terms = phrase.split(' ');
  for (i = 0; i < terms.length; i++) {
    if (terms[i].toUpperCase() == 'WISH'){
      count++;
    }
  }
  return count;
}

请注意,您还可以使用Array.reduce简化代码。将字符串拆分为数组后,仅过滤那些值为“ wish”的数组值,然后返回过滤后的数组的长度。

var msg = 'I wish to wish the WISH you wish to wish but if you wish '
+ 'the WISH the witches wish I won\'t wish the WISH you wish '
+ 'to wish';
document.writeln('Found ' + countTerms(msg) + ' wishes.');
function countTerms(phrase) {
  return phrase.split(' ').filter(p => p.toUpperCase() === 'WISH').length;
}

答案 1 :(得分:0)

您始终总是直接return直接访问第一个count,该点此时为0。为了保持计数,只需在循环中执行count++,并在循环完成后进行return count;

答案 2 :(得分:0)

不要在循环内返回

for (i = 0; i < terms.length - 1; i++){
    if (terms[i].toUpperCase() == 'WISH'){
       count++;
    }
}

// Return hear
return count;

答案 3 :(得分:0)

这是因为您要退回预 -增量值。这意味着在return语句完成运行之前,不会更新变量。要修改您的代码,请更改

return count++

对此

count++

,然后在for循环之后,在函数底部返回count。

答案 4 :(得分:0)

有两个错误。循环后返回计数。 另一个在for循环中:您使用i

var msg = 'I wish to wish the WISH you wish to wish but if you wish ' +
  'the WISH the witches wish I won\'t wish the WISH you wish ' +
  'to wish';
  
console.log('Found ' + countTerms(msg) + ' wishes.');

function countTerms(phrase) {
  var count = 0;
  var terms = phrase.split(' ');
  for (let i = 0; i < terms.length; i++) {
    if (terms[i].toUpperCase() === 'WISH') {
      count++;
    }
  }
  return count;
}