JavaScript中如何获取数组的平均值

0 javascript arrays for-loop

我正在编写一个代码,让您可以在提示窗口中输入 10 个随机数字。这些数字存储在名为 的数组中tal。我已经弄清楚如何获得最高值和最低值,但我无法获得平均值。有人可以帮助我找到解决方案或让我走上正确的道路吗?

这是我的代码:

let tal = [];
for (i = 0; i < 10; i++) {
  tal[i] = prompt('Add a number: ', '');
  tal.sort(function(a, b) {
    return a - b
  });
}
document.body.innerHTML += Math.max.apply(null, tal) + '<br>';
document.body.innerHTML += Math.min.apply(null, tal) + '<br>';
Run Code Online (Sandbox Code Playgroud)

nor*_*ial 6

我认为,如果你reduce()先对数字进行求和,然后将该数字除以长度,最后就会得到数字的平均值。

来自以下文档Array.prototype.reduce()

reduce() 方法对数组的每个元素执行(您提供的)reducer 函数,从而产生单个输出值。

const numbers = [3,4,5,2,4,6,78,53,2,1,2];
const sum = numbers.reduce((a,c) => a + c, 0);
const avg = sum / numbers.length;

console.log(avg);
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!