数组中的范围数字

Range numbers in array

我写了一个函数,它根据给定的数字范围创建一个数组,但它不起作用。

function makeListFromRange(start, end) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}

const result = makeListFromRange([2, 7]); // should be [2, 3, 4, 5, 6, 7]

console.log(result);

您的函数需要两个参数,每个参数都应该是一个数字。要传入长度为 2 的数组,需要使用展开运算符 (...).

function makeListFromRange(start, end) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}

const result = makeListFromRange(...[2, 7]); // should be [2, 3, 4, 5, 6, 7]

console.log(result);

如果输入需要是数组,使用数组解构得到startend:

function makeListFromRange([start, end]) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}

const result = makeListFromRange([2, 7]); // should be [2, 3, 4, 5, 6, 7]

console.log(result);

一个更简单的解决方案是提供 startend 作为参数:

function makeListFromRange(start, end) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}

const result = makeListFromRange(2, 7); // should be [2, 3, 4, 5, 6, 7]

console.log(result);