javascript - 用平均值填充数组
问题描述
我想知道我在 Javascript 中遇到的问题。我有一个场景,我需要用周围值的平均值填充数组中的空白。让我举个例子:
数组:1, 2, 3, ,4, 5
在这种特殊情况下,我需要用周围数字的平均值来填补空白,即 3.5。我认为这相对容易做到。
但是,我还需要确保当数组中存在更多后续间隙时此方法有效。
示例:1, 2, 3, , , 5, 6
在这种情况下,两个间隙应该用 3 和 5 的平均值来填充,结果是...... 3, 4, 4, 5。
我被卡住的那一刻是当我尝试迭代数组并填补空白时,因为我用 4 填补了第一个空白,但在那一刻,第二个空白的周围数字是 4(原始空白)和 5,所以我结束了与
... 3, 4, 4.5, 5, ...
这不是我需要的。
我使用 jQuery 迭代数组并从表中获取值。
这就是我加载数组的方式:
var list = [];
$('#mytable > tbody > tr').each(function() {
$this = $(this);
list.push(eval($this.find("input.number").val());
}
现在我需要迭代并填补“列表”中的空白
解决方案
这是一种可能的实现:
function fill(arr) {
while (arr.includes(undefined)) {
const startIndex = arr.findIndex(num => num === undefined);
const endIndex = arr.findIndex((num, i) => i >= startIndex && num !== undefined);
const avg = (arr[startIndex - 1] + arr[endIndex]) / 2;
for (let i = startIndex; i < endIndex; i++) arr[i] = avg;
}
return arr;
}
console.log(fill([1, 2, 3, , , 5, 6]));
console.log(fill([1, , , , , , 6]));
console.log(fill([1, , , , 3, 4, , , 6]));
推荐阅读
- android - 相同的选项菜单超过活动,无效的方法声明;需要返回类型
- java - 如何在 Gmail SMTP 中指定显示名称?
- prolog - 在序言中多次避免相同的答案
- deep-learning - 如何使用 RNN 使用 6 个时间步来预测接下来的 4 个时间步
- excel - 用总和 Excel 偏移
- python - 如何检查数字列表是否在python中的2个值之间?
- python - 如何将列表元素作为索引号在 Python 中打印另一个列表?
- java - recyclerView android上只能点击一项
- kubernetes - NetworkPolicy 无法限制来自 UI 的 Ingress
- javascript - 将条带结帐与 .net 集成