我有一个六个引号的数组,我试图找到每个引号的平均长度。我想我需要创建一个新的字符串长度数组,然后平均。但我无法弄清楚如何将原始数组的数量放入新数组中。我如何获得第一个数组的数量到新的数组?查找数组中字符串的平均字符串长度 - Javascript
1
A
回答
2
0
您可以使用Array.prototype.reduce
总结所有报价的总长度并通过报价数组的长度/大小将其划分:
const quotes = [
"Quote #1",
"Longer quote",
"Something...",
...
];
// Sum up all the quotes lengths
const totalQuotesLength = quotes.reduce(function (sum, quote) {
return sum + quote.length;
}, 0);
// Calculate avg length of the quotes
const avgQuoteLength = (
totalQuotesLength/quotes.length
);
0
如果我的理解没错,你要查找的平均长度数组中的字符串,你可以这样做:
var total = 0;
for(var i = 0; i < array.length; i++){
total+=array[i].length;
}
var average = total/array.length;
2
0
你可以简单地也.reduce
使用的东西,如:
const numbers = [1,2,3,4,5,6];
const total = numbers.reduce((acc, value) => acc + value, 0);
const average = total/numbers.length;
我锄它将帮助!
0
您可以在每个元素上使用forEach而不创建新数组。可能很长,但阅读:
https://jsfiddle.net/p19qbodw/ - 在打开控制台运行此看到的结果
var quotes = ["quotequote", "quote", "qu"]
charsSum = 0,
avarage;
quotes.forEach((el) => {
charsSum += el.length;
});
avarage = charsSum/quotes.length;
0
全部加入数组值到一个字符串,然后你可以计算平均长度。
var yourArray = ["test", "tes", "test"],
arrayLength = yourArray.length,
joined = yourArray.join(''),
result = joined.length/arrayLength;
console.log(result);
相关问题
- 1. Typescript字符串|字符串[]查找数组长度
- 2. 查找字符串数组中最长的字符串
- 3. 查找字符串中所有子字符串的长度
- 4. 查找最长字符串的长度
- 5. 发现平均字长字符串
- 6. SQL:查找数据字符串中的动态长度字符
- 7. 查找字符串中的所有3个字符长度的子字符串
- 8. 字符串数组中字符串的长度
- 9. 查找字符串数组的平均值
- 10. 函数在cpp中查找2d字符串数组的长度?
- 11. 查找multiplicy长度的字符串
- 12. 查找字符串的长度
- 13. 查找字符串的二维数组中的字符串数
- 14. ArrayList:获取最长字符串的长度,获取字符串的平均长度
- 15. 查找字符串中字符之间的长度
- 16. 如何获取字符串数组的字符串长度?
- 17. 字符串的长度比字符串的长度长
- 18. 给定一个字符串数组,将所有字符串的长度均替换为空字符串
- 19. Javascript:检查最小字符串长度
- 20. 计算字符串中单词的平均长度
- 21. 查找字符串数组中的字符串的一部分
- 22. 查找包含字符串数组中子字符串的所有字符串
- 23. 查找字符串中的字符串
- 24. 查找字符串中的字符串
- 25. 查找字符串中的字符串
- 26. 从字符串值中查找特定的字符串数组
- 27. 查找字符串数组中的字符串
- 28. 在2d字符串数组中查找重复的字符串
- 29. 查找字符串/数组中的字符串
- 30. 优化查找字符串数组中最宽的字符串?
你可以用引号括起你的数组。 –