涉及从字符串中平均字长的函数?(Function that involves averaging word length from a string?)

编程入门 行业动态 更新时间:2024-10-26 08:24:47
涉及从字符串中平均字长的函数?(Function that involves averaging word length from a string?)

这是我第一次接触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;

更多推荐

本文发布于:2023-08-07 03:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   函数   平均   Function   involves

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!