创建一个以一定数量的项目为起点的序列数组

时间:2021-08-15 17:03:03

Is there an elegant way (without a for loop) to create a sequential array in Javascript which starts from a certain number and has a certain numbers of items. for example:

是否有一种优雅的方法(没有for循环)在Javascript中创建一个顺序数组,它从一个特定的数字开始,并且有一定数量的条目。例如:

Start from 2017 and has 4 items will look like:

从2017年开始,有4个项目将会是:

[2017, 2018, 2019, 2020]

thanks

谢谢

1 个解决方案

#1


6  

You could use Array.from with a callback for the values.

您可以使用Array.from作为值的回调。

The Array.from() method creates a new Array instance from an array-like or iterable object.

方法的作用是:从类数组或可迭代对象中创建一个新的数组实例。

[...]

[…]

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

from()有一个可选参数mapFn,允许您在创建的数组(或子类对象)的每个元素上执行映射函数。更清楚的是,Array.from(obj, mapFn, thisArg)与Array.from(obj).map(mapFn, thisArg)有相同的结果,只是它不创建一个中间数组。这对于某些数组子类(如类型化数组)尤其重要,因为中间数组的值必须被截断,以适应适当的类型。

var items = 4,
    start = 2017,
    array = Array.from({ length: items }, (_, i) => start + i);

console.log(array);

#1


6  

You could use Array.from with a callback for the values.

您可以使用Array.from作为值的回调。

The Array.from() method creates a new Array instance from an array-like or iterable object.

方法的作用是:从类数组或可迭代对象中创建一个新的数组实例。

[...]

[…]

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

from()有一个可选参数mapFn,允许您在创建的数组(或子类对象)的每个元素上执行映射函数。更清楚的是,Array.from(obj, mapFn, thisArg)与Array.from(obj).map(mapFn, thisArg)有相同的结果,只是它不创建一个中间数组。这对于某些数组子类(如类型化数组)尤其重要,因为中间数组的值必须被截断,以适应适当的类型。

var items = 4,
    start = 2017,
    array = Array.from({ length: items }, (_, i) => start + i);

console.log(array);