我有一個六個引號的數組,我試圖找到每個引號的平均長度。我想我需要創建一個新的字符串長度數組,然後平均。但我無法弄清楚如何將原始數組的數量放入新數組中。我如何獲得第一個數組的數量到新的數組?查找數組中字符串的平均字符串長度 - 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. 優化查找字符串數組中最寬的字符串?
你可以用引號括起你的數組。 –