Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

后端 未结 30 3255
广开言路
广开言路 2020-11-22 00:51

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range(\"A\", \"C\"); // Array(\"A\", \"B\", \"C\")

That is, there is a function that l

30条回答
  •  执笔经年
    2020-11-22 01:56

    For numbers you can use ES6 Array.from(), which works in everything these days except IE:

    Shorter version:

    Array.from({length: 20}, (x, i) => i);
    

    Longer version:

    Array.from(new Array(20), (x, i) => i);​​​​​​
    

    which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:

    Array.from(Array(20).keys());
    // or
    [...Array(20).keys()];
    

    Lower and upper bounds can be specified too, for example:

    Array.from(new Array(20), (x, i) => i + *lowerBound*);
    

    An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

提交回复
热议问题