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

时间:2016-09-01 20:08:30

标签: javascript object for-loop count

我正在进行编码练习并且难以理解这个功能。我正在尝试创建的函数是接受一个字符串,记录每个单词的重复次数。问题是当我尝试使用myObject.key = value添加到对象中时,在传递var count时,放入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'));

有些印刷语句可能是不必要的,但理解这可能会有所帮助,所以我把它留在了。

2 个答案:

答案 0 :(得分:1)

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

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

如果您已经获得了一个值,那么你可以通过不打算计算一个单词来提高效率(因为你肯定会在以后的实例中获得更少的数量)

答案 1 :(得分:0)

for (var j=i+1; j<myArray.length; j++) {整个问题是由j = i + 1引起的,因为这将导致对象&#39;将值设置为0,因为除非currentWordnextWord变为true,否则finalCount将变为0。

根据我对你的函数名的理解,你想要一个字符串,找出每个单词的实例数。

这是一个清理工作小提琴的一些评论: https://jsfiddle.net/gzqm5k0d/

相关问题