javascript - 使用 'count' 变量添加到对象时,var 'count' 仍然为 0

标签 javascript object for-loop count

我正在进行编码练习,并对这个函数感到困惑。我试图创建的函数是接受一个字符串,记录每个单词的重复次数。问题是当我尝试使用 myObject.key = value 添加到对象中时,在传递 var 计数时,放入 myObject 中的计数仍然为 0,即使它正在更新。

function countWords(string) {
  var myArray = string.split(" ");
  var myObject = {};

  for (var i=0; i<myArray.length; i++) {
    var currentWord = myArray[i];
    //var count2 = 0;
    var count = 0;
    
    for (var j=i+1; j<myArray.length; j++) {
      var nextWord = myArray[j];
      console.log(currentWord + ' and a ' + nextWord)
      console.log('countBefore: '+count)
      if (currentWord===nextWord) {
        count += 1;
      }
      console.log('countAfter: '+count)
    }//for loop2
    
    console.log('countOutside: '+count)
    myObject[currentWord] = count;
  }// for loop
  
  return myObject;
}

//console.log(countWords('blah blah the the the he she be'));
console.log(countWords('blah blah the the the she'));

一些打印语句可能是不必要的,但可能有助于理解,因此我将其保留。

最佳答案

我认为问题在于每个单词都会覆盖其之前任何相同单词的计数。因此,您要么需要在计数后删除每个单词,要么仅在新值更高时才更改特定单词的计数值。

function countWords(string) {
  var myArray = string.split(" ");
  var myObject = {};

  for (var i=0; i<myArray.length; i++) {
    var currentWord = myArray[i];
    //var count2 = 0;
    var count = 0;

    for (var j=i+1; j<myArray.length; j++) {
      var nextWord = myArray[j];
      if (currentWord===nextWord) {
        count += 1;
      }
    }
    if (!myObject[currentWord] ||count > myObject[currentWord]){
      myObject[currentWord] = count;
    }
  }// for loop

  return myObject;
}

//console.log(countWords('blah blah the the the he she be'));
console.log(countWords('blah blah the the the she'));

如果您已经获得了单词的值,那么您可以通过不费心去计算单词来提高效率(因为您在以后的实例中肯定会得到更小的计数)

关于javascript - 使用 'count' 变量添加到对象时,var 'count' 仍然为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280093/

相关文章:

php - 为什么 var_dump 可以确定私有(private)变量的值,但在尝试访问单个属性时却不能

c - 为什么我的 for 循环是无限循环 (C)?

java - 我对代码段的运行时分析是否正确?

class - Android Studio 内的对象浏览器

javascript - 动态传递父对象作为 JavaScript 中的参数

javascript - 云函数: Crop image > Resize to multiple sizes

javascript - 背景图像交换动画

python - 在函数定义中放置变量 - Python

javascript - 在 PHP 子串中返回 �� 这些类型的字符?

javascript - jquery中如何去掉页眉和页面内容之间的空格?