gpt4 book ai didi

javascript - 创建一个顺序数组,从一定数量开始,有一定数量的项目

转载 作者:行者123 更新时间:2023-11-29 16:05:23 28 4
gpt4 key购买 nike

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

2017 开始,有 4 项将如下所示:

[2017, 2018, 2019, 2020]

谢谢

最佳答案

你可以使用 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.

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

console.log(array);

关于javascript - 创建一个顺序数组,从一定数量开始,有一定数量的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44304904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com