Array = [0, 4, 10, -20, 10, 20, 50]
我想要这个数组在一个公式之后,使它看起来像这样或类似
Array = [0, 2, 4, 7, 10, -5, -20, -5, 10, 15, 20, 35, 50]
它所做的是,检查数字之间的距离,然后将距离除以2,然后将其添加到这些值的中间。
发布于 2021-04-10 08:06:56
您可以迭代数组(例如,使用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);
发布于 2021-04-10 08:05:13
可以将数组映射到二维数组,然后将其展平。
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);
发布于 2021-04-10 08:08:42
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)
https://stackoverflow.com/questions/67031999
复制相似问题