这是我第一次接触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"我知道我在某种程度上需要我的长度,但我试图应用length每一种方式都没有用。
想法?
谢谢!
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!
最满意答案
你几乎拥有它,只需要几个小的改动,你的代码就可以运行得很好。
wordArray应声明如下:
var wordArray = x.split(" ");然后,您需要将单词字符长度的总和更正为wordAvg 。
改变这个:
wordAvg += wordArray[i];对此:
wordAvg += wordArray[i].length;You almost had it, just a couple small changes and your code works great.
wordArray should be declared as follows:
var wordArray = x.split(" ");Then you need to correct the summation of the word character lengths to wordAvg.
Change this:
wordAvg += wordArray[i];To this:
wordAvg += wordArray[i].length;更多推荐
发布评论