如何仅在 ES2015 中生成从 0 到 n 的数字范围? [英] How to generate range of numbers from 0 to n in ES2015 only?
问题描述
我总是发现 JavaScript 中缺少 range
函数,因为它在 Python 和其他版本中可用?在 ES2015 中是否有任何简洁的方法来生成数字范围?
I have always found the range
function missing from JavaScript as it is available in python and others? Is there any concise way to generate range of numbers in ES2015 ?
我的问题与提到的重复不同,因为它特定于 ES2015 而不是 ECMASCRIPT-5.此外,我需要范围从 0 开始,而不是特定的起始数字(尽管如果有它会很好)
MY question is different from the mentioned duplicate as it is specific to ES2015 and not ECMASCRIPT-5. Also I need the range to be starting from 0 and not specific starting number (though it would be good if that is there)
推荐答案
您可以对新创建的数组的键使用扩展运算符.
You can use the spread operator on the keys of a freshly created array.
[...Array(n).keys()]
或
Array.from(Array(n).keys())
Array.from()
语法在使用 TypeScript 时是必需的
The Array.from()
syntax is necessary if working with TypeScript
这篇关于如何仅在 ES2015 中生成从 0 到 n 的数字范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!