首页 > 解决方案 > 这个 forEach 循环有什么问题?它不能正常运行

问题描述

let unnecessaryWords = ['extremely', 'literally', 'actually'];

storyWords = story.split(' ')


let betterWords = storyWords.filter(function (word) {
  return !unnecessaryWords.includes(word)
})


let reallyCount = 0
let basicallyCount = 0
let veryCount = 0
for (i = 0; i < storyWords.length; i += 1) {
  if (betterWords[i] == 'really') {
    reallyCount += 1}
  if (betterWords[i] == 'basically') {
      basicallyCount += 1}
  if (betterWords[i] == 'very') {
        veryCount += 1}
      }

console.log('Really Count : ', reallyCount)
console.log('Basically Count : ', basicallyCount)
console.log( 'Very Count : ', veryCount)

let sentencesCount = 0
storyWords.forEach(word =>{
  if(word[word.length - 1] === "." || word[word.length - 1] === "!"){
    sentencesCount =+ 1
  }

});
console.log(sentencesCount)

预期结果应该是 12,但它显示为 1。

句数统计功能代码有误。任何人都可以提出解决这个问题的方法吗?问题出在最后一个 forEach 循环中。另外我需要询问是否有其他方法可以解决这个问题。

标签: javascriptloopsforeach

解决方案


代码中的错字:

sentencesCount += 1

我建议使用增量运算符:

sentencesCount++;

推荐阅读