相邻元素平均值的数组 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 15:08:17
假设我们有一个数字数组 −
const arr = [3, 5, 7, 8, 3, 5, 7, 4, 2, 8, 4, 2, 1];
我们需要编写一个函数,返回一个数组,其中包含相应元素及其前身的平均值。对于第一个元素,由于没有前身,因此应该返回该元素。
让我们为这个函数编写代码,我们将使用 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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

