首页 > 解决方案 > 用平均值填充数组

问题描述

我想知道我在 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());
}

现在我需要迭代并填补“列表”中的空白

标签: javascriptjqueryarrays

解决方案


这是一种可能的实现:

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]));


推荐阅读