[英]Using array.prototype.map with average function
閱讀有關map方法的文檔后,我仍然無法使它正常工作。 我正在嘗試使用map獲取數組中每對數字的平均值。請幫助我了解錯誤之處。
function getAverage(num1,num2){return Math.ceil((num1+num2)/2)};
function a(input){ var b = input.map(getAverage(num1,num2)); return b; }
a([1,2,3,4]) //error num1 is not defined
//expected [2,4]
map
將函數投影到列表/數組的每個元素上,它只是將函數“映射”到所有項目上。
[1, 2, 3].map(function (number) { return number + 1; });
// -> [2, 3, 4]
因此,首先您需要在“輸入”數組中具有成對的項目,因此看起來像這樣:
var numberPairs = [[1, 2], [3, 4]]
到現在為止,您所擁有的只是一個數字而沒有對。
轉換后,您可以使用如下map
:
numberPairs.map(function (pair) {
return Math.ceil((pair[0] + pair[1]) / 2);
});
這將給出:
[2, 4]
結果是。
您無法使用地圖計算平均值。 映射將函數傳遞給每個元素,然后返回具有相同形狀的數組。 事實並非如此,您想從數組中獲取一個值,然后可以使用reduce方法 。
// adds two number const adder = (a,b) => a + b; // reduces the array adding all numbers and divides // by the array length const getAverage = (arr) => arr.reduce(adder)/arr.length; // outputs 2.5 console.log(getAverage([1,2,3,4]))
您可以使用reduce()
而不是map()
來匯總數組中每n
值的平均值:
const sum = array => array.reduce((a, b) => a + b, 0) const getAverage = n => (averages, value, index, array) => index % n === 0 ? [...averages, Math.ceil(sum(array.slice(index, index + n)) / n)] : averages const result = [1, 2, 3, 4].reduce(getAverage(2), []) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.