This is my first time ever touching JavaScript, and I am writing a function that will output the following:
- Individual words in the string,
- Total character count,
- Total word count,
- Whitespace count,
- and finally the average word length.
So far I have all aspects complete except I am struggling with the averaging process.
My code:
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");
I like everything as it is except the averaging.
Output:
"Words: This,function,will,analyze,strings"
"Character count: 34"
"Word count: 5"
"Whitespace count: 4"
"Word length average: 0"
I know I somehow need the length of i
, but every way I have attempted to apply length
hasn't worked.
Ideas?
Thank you!
You almost had it, just a couple small changes and your code works great.
wordArray
should be declared as follows:Then you need to correct the summation of the word character lengths to
wordAvg
.Change this:
To this: