JavaScript 中元素对的累计平均值

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/3 15:08:17

我们有一个数字数组,需要编写一个函数,该函数返回一个数组,其中包含相应元素及其前身的平均值。

对于第一个元素,由于没有前身,因此应该返回该元素。

让我们为该函数编写代码,我们将使用 Array.prototype.map() 函数来解决这个问题。

示例

其代码为 −

const arr = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];
const consecutiveAverage = arr => {
   return arr.map((el, ind, array) => {
      const first = (array[ind-1] || 0);
      const second = (1 + !!ind);
      return ((el + first) / second);
   });
};
console.log(consecutiveAverage(arr));

输出

控制台中的输出将是 −

[
   3, 4, 6, 7.5, 5.5, 4,
   6, 5.5, 3, 5, 6, 3,
   1.5
]

相关文章


有用资源