如何将数组中的每组数字相加?(javascript)

How to add each set of numbers within an array of arrays? (javascript)

本文关键字:javascript 数字 数组      更新时间:2023-09-26

我正在努力设计一个循环,它将循环通过一个数组,并将每个数字相加,计算出平均值,然后输出到控制台。

这是我的密码;

var data = [
  [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95],
  [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93],
  [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80],
  [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97],
  [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88],
  [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99]
]
var calcTotal, arrayTotal, totalSum;
calcTotal = [];
arrayTotal = [];
totalSum = [];
arrayTotal.push(data[0])
totalSum = data[0].reduce(function(a, b) {
  return a + b;
});
calcTotal.push(totalSum)
console.log(Math.round(totalSum / 12))

http://plnkr.co/edit/Ses4XApKEdo2CCZmsis7?p=preview

到目前为止,我只显示一个结果,理想情况下,我会将每个数组的平均值添加到控制台的单个数组中。

我一直在玩for/forEach循环,但似乎无法破解,如果有人能提供一些帮助/建议的话?

感谢

这很容易:您可以编写两个函数,addaverage,使用Array#mapArray#reduce:

var data = [
  [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95],
  [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93],
  [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80],
  [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97],
  [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88],
  [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99]
];
function add(a, b) {
  return a + b;
}
function average(list) {
  return list.reduce(add) / list.length;
}
document.body.textContent = data.map(average);

据我所知,您需要向控制台显示每行的平均值,对吗?

你在单行方面做得很好,只需要把它打包就行了。下面是工作小提琴:https://jsfiddle.net/enowacki/dhdc1ztc/2/

const data = [
  [3, 6, 14, 17, 30, 40, 44, 66, 69, 84, 92, 95],
  [100, 17, 26, 28, 29, 34, 38, 59, 78, 82, 84, 93],
  [6, 12, 22, 25, 35, 44, 45, 57, 60, 61, 78, 80],
  [6, 11, 14, 19, 33, 50, 57, 58, 61, 88, 89, 97],
  [6, 13, 23, 28, 39, 44, 50, 55, 58, 72, 80, 88],
  [6, 8, 22, 26, 48, 50, 55, 65, 77, 84, 93, 99]
];
const result = data.map((arr) => {
  const rowSum = arr.reduce((prev, curr) => prev + curr);
  const rowCount = arr.length;
  const avg = Math.round(rowSum / rowCount);
  
  return avg;
});
console.log(result);

我提取了一些额外的变量,这样你就可以清楚地看到发生了什么,如果不需要的话,可以省略它们。

压扁:

var flat = [].concat.apply([], data);

总和:

var sum = flat.reduce((a, b) => a+b, 0);
console.log("Avg:" + Math.round(sum / flat.length);