寻找连续元素的平均值 JavaScript
假设我们有一个数字数组 −
const arr = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];
我们需要编写一个函数,返回包含对应元素及其前继元素的平均值的数组。对于第一个元素,因为没有前继元素,所以应该返回该元素本身。
让我们编写这个函数的代码,我们将使用 Array.prototype.map() 函数来解决这个问题 −
示例
const consecutiveAverage = arr => { return arr.map((el, ind, array) => { return ((el + (array[ind-1] || 0)) / (1 + !!ind)); }); }; console.log(consecutiveAverage(arr));
输出
控制台中的输出为 −
[ 3, 4, 6, 7.5, 5.5, 4, 6, 5.5, 3, 5, 6, 3, 1.5 ]
广告