查找连续元素平均值 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/13 2:52:17

假设我们有一个数字数组 −

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
]

相关文章


有用资源