涉及从字符串中平均字长的函数?

时间:2015-06-22 17:30:52

标签: javascript function for-loop average

这是我第一次接触JavaScript,我正在编写一个输出以下内容的函数:

  • 字符串中的单词
  • 总字符数,
  • 总字数,
  • 空白数,
  • 最后是平均字长。

到目前为止,我已经完成了所有方面,除非我在平均过程中苦苦挣扎。

我的代码:

var superCounter = function(x) {
  var charCount = x.length;
  var wordCount = x.split(" ").length;
  var whiteSpace = wordCount - 1; 
  var wordArray = [x.split(" ")];
  var wordAvg = 0;
  for (var i = 0; i < wordCount.length; i++){
    wordAvg += wordArray[i];
  }
  var avgLen = wordAvg / wordCount;
  console.log(("Words: " + wordArray[0]), "Character count: " + charCount, "Word count: " + wordCount, "Whitespace count: " + whiteSpace, "Word length average: " + avgLen);
};

superCounter("This function will analyze strings");

我喜欢除了平均之外的一切。

输出:

"Words: This,function,will,analyze,strings"
"Character count: 34"
"Word count: 5"
"Whitespace count: 4"
"Word length average: 0"

我知道我需要i的长度,但我试图应用length的每一种方式都没有用。

想法?

谢谢!

4 个答案:

答案 0 :(得分:5)

你几乎拥有它,只需要进行一些小改动,你的代码就可以运行得很好。

wordArray应声明如下:

var wordArray = x.split(" ");

然后,您需要将单词字符长度的总和更正为wordAvg

改变这个:

wordAvg += wordArray[i];

对此:

wordAvg += wordArray[i].length;

答案 1 :(得分:1)

 wordAvg += wordArray[i];

应该是

 wordAvg += wordArray[i].length;

答案 2 :(得分:1)

应该是这样的:

var superCounter = function(x) {
    var charCount = x.length;
    var wordCount = x.split(" ").length;
    var whiteSpace = wordCount - 1; 
    var wordArray = x.split(" ");
    var wordAvg = 0;
    for (var i = 0; i < wordCount; i++){
        wordAvg += wordArray[i].length;
    }
    var avgLen = wordAvg / wordCount;
    console.log(("Words: " + wordArray), "Character count: " + charCount, "Word count: " + wordCount, "Whitespace count: " + whiteSpace, "Word length average: " + avgLen);
};

superCounter("This function will analyze strings");

答案 3 :(得分:0)

也许尝试这样的事情:

 function jCounter(data) { 
     var strArr = data.split(' ');
     var strChar = data.length;
     var objStr = strArr.length;   
     var strSpaces = objStr - 1;

     var numArr = [];
     for (i=0; i<objStr; i++) {
        numArr.push(strArr[i].length); 
     }

     var sum = 0;
     for (i=0; i<numArr.length; i++) {
        sum = sum + numArr[i];
     } 

     var avg = sum/objStr;
     var strObj = {}; 

     strObj.words = objStr;
     strObj.chars = strChar;
     strObj.avgLength = avg ;
     strObj.spaces = strSpaces;

     console.log(strObj);
   } 

   jCounter("Coding is challenging");