使用数字 +10/-10 创建数组,其中中间一个为 0,具体取决于我想要的长度

Create array with numbers +10/-10, where middle one is 0, depending on what length I want

我需要动态创建数组,只知道我想要它有多长。例如,我需要数组长度为 3,所以我需要数组 = [-10, 0, 10],如果我需要数组长度为 9,它将是 [-40, -30, -20, -10, 0, 10, 20, 30, 40] 等。我怎样才能自动完成?

您可以简单地使用 Arrayfill

得到结果

因为您只想 0 在中心,所以输入应该是 odd

const end = 9;
let start = Math.floor(end / 2);

const result = [
  ...Array(start).fill(0).map((_, i) => start * -10 + i * 10),
  0,
  ...Array(start).fill(0).map((_, i) => (i + 1) * 10)
]

console.log(result)

另一个解决方案Array.from

const createArray = (length) => Array.from({length}, (el, i) => Math.round(i - length / 2) * 10);

console.log(createArray(1))
console.log(createArray(3))
console.log(createArray(9))