查找数组中字符串的平均字符串长度 - Javascript
Finding Average String Length of Strings in Array - Javascript
我有一个包含六个引号的数组,我正在尝试找出每个引号的平均长度。我在想我需要创建一个新的字符串长度数组,然后取平均值。但我不知道如何将原始数组的计数放入新数组中。如何将第一个数组的计数放入新数组中?
您可以使用 Array.prototype.reduce
来总结所有报价的总长度,然后将其除以报价数组的 length/size:
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
);
如果我没理解错,你想求一个数组中字符串的平均长度,你可以这样做:
var total = 0;
for(var i = 0; i < array.length; i++){
total+=array[i].length;
}
var average = total/array.length;
您可以 reduce
您的字符串数组。例如:
['a', 'bb', 'ccc', 'dddd']
.reduce((a, b, i, arr) => a + b.length / arr.length, 0)
您也可以简单地将 .reduce
与类似的东西一起使用:
const numbers = [1,2,3,4,5,6];
const total = numbers.reduce((acc, value) => acc + value, 0);
const average = total / numbers.length;
我希望它会有所帮助!
您可以在每个元素上使用 forEach 而无需创建新数组。可能很长但可读:
https://jsfiddle.net/p19qbodw/ - 运行 在打开的控制台中查看结果
var quotes = ["quotequote", "quote", "qu"]
charsSum = 0,
avarage;
quotes.forEach( (el) => {
charsSum += el.length;
});
avarage = charsSum/quotes.length;
arr = [1, 12, 123, 1234] // works with numbers too
avg = arr.join('').length / arr.length // 10 / 4 = 2.5
console.log(avg)
将所有数组值连接到一个字符串,然后您可以计算平均长度。
var yourArray = ["test", "tes", "test"],
arrayLength = yourArray.length,
joined = yourArray.join(''),
result = joined.length / arrayLength;
console.log(result);
我有一个包含六个引号的数组,我正在尝试找出每个引号的平均长度。我在想我需要创建一个新的字符串长度数组,然后取平均值。但我不知道如何将原始数组的计数放入新数组中。如何将第一个数组的计数放入新数组中?
您可以使用 Array.prototype.reduce
来总结所有报价的总长度,然后将其除以报价数组的 length/size:
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
);
如果我没理解错,你想求一个数组中字符串的平均长度,你可以这样做:
var total = 0;
for(var i = 0; i < array.length; i++){
total+=array[i].length;
}
var average = total/array.length;
您可以 reduce
您的字符串数组。例如:
['a', 'bb', 'ccc', 'dddd']
.reduce((a, b, i, arr) => a + b.length / arr.length, 0)
您也可以简单地将 .reduce
与类似的东西一起使用:
const numbers = [1,2,3,4,5,6];
const total = numbers.reduce((acc, value) => acc + value, 0);
const average = total / numbers.length;
我希望它会有所帮助!
您可以在每个元素上使用 forEach 而无需创建新数组。可能很长但可读:
https://jsfiddle.net/p19qbodw/ - 运行 在打开的控制台中查看结果
var quotes = ["quotequote", "quote", "qu"]
charsSum = 0,
avarage;
quotes.forEach( (el) => {
charsSum += el.length;
});
avarage = charsSum/quotes.length;
arr = [1, 12, 123, 1234] // works with numbers too
avg = arr.join('').length / arr.length // 10 / 4 = 2.5
console.log(avg)
将所有数组值连接到一个字符串,然后您可以计算平均长度。
var yourArray = ["test", "tes", "test"],
arrayLength = yourArray.length,
joined = yourArray.join(''),
result = joined.length / arrayLength;
console.log(result);