![](/img/trans.png)
[英]How to splice an array and add random numbers to each array index in JavaScript
[英]How to add each set of numbers within an array of arrays? (javascript)
我正在努力設計一個循環,該循環將遍歷數組數組並將每個數字加在一起,計算出平均值然后輸出到控制台。
這是我的代碼;
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循環,但是如果有人可以提供一些幫助/建議,似乎無法破解它?
謝謝
這很簡單:您可以編寫兩個函數add
和average
,使用Array#map
和Array#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);
據我了解,您需要向控制台顯示每行的平均值,對不對?
您已經用單行完成了相當不錯的工作,只需將其與forEach打包在一起,就可以使用這里的小提琴: 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.