如何使值更长的数组 (JavaScript)

How to make an array with values longer (JavaScript)

Array = [0, 4, 10, -20, 10, 20, 50]

我希望这个数组在公式之后看起来像这样或类似

Array = [0, 2, 4, 7, 10, -5, -20, -5, 10, 15, 20, 35, 50] 

它所做的是检查数字之间的距离,然后将距离除以 2,然后将其添加到这些值的中间。

可以将数组映射成二维数组,然后展平。

const arr = [0, 4, 10, -20, 10, 20, 50];

const res = arr
  .map((a, i) => [a, (arr[i + 1] + a) / 2])
  .flat()
  .slice(0, -1);

console.log(res);

您可以遍历数组(例如使用 forEach),同时将值和中间值推入新数组:

const arr = [0, 4, 10, -20, 10, 20, 50];

const res = [];
arr.forEach((v, i) => {
  if (i != 0) res.push((v + arr[i - 1]) / 2);
  res.push(v);
});

console.log(res);

您也可以使用 flatMap,通过映射数组然后展平结果同时创建两个条目:

const arr = [0, 4, 10, -20, 10, 20, 50];

const res = arr.flatMap((v, i) => i == 0 ? v : [(v + arr[i - 1]) / 2, v]);

console.log(res);

您也可以(正如 Som 在评论中所建议的那样)在 i == 0 时忽略数组索引问题,只切掉生成的 NaN 值:

const arr = [0, 4, 10, -20, 10, 20, 50];

const res = arr.flatMap((v, i) => [(v + arr[i - 1]) / 2, v]).slice(1);

console.log(res);

const array = [0, 4, 10, -20, 10, 20, 50]

const newArray = []

array.forEach((arr, idx) => {
  newArray.push(arr)
  if (idx <= array.length - 2) {
    newArray.push((array[idx + 1] + arr) / 2)
  }
})

console.log(newArray)

另一个选项可以使用 concat 作为距离和当前值。

const arr = [0, 4, 10, -20, 10, 20, 50];
let res = [];

arr.forEach((v, i) => res = i > 0 ? res.concat([(v + arr[i - 1]) / 2, v]) : [v]);

console.log(res);