如何在ES2015中生成从0到n的数字范围? [英] How to generate range of numbers from 0 to n in ES2015 only?
问题描述
我一直发现JavaScript中缺少范围
的功能,因为它在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)
推荐答案
我还发现一个更直观的方式使用 Array.from
:
I also found one more intuitive way using Array.from
:
const range = n => Array.from({length: n}, (value, key) => key)
这个范围
函数将返回从0开始到n-1的所有数字
Now this range
function will return all the numbers starting from 0 to n-1
范围的修改版本支持开始
和结束
是:
A modified version of the range to support start
and end
is:
const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);
这篇关于如何在ES2015中生成从0到n的数字范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!