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

后端 未结 30 2767
广开言路
广开言路 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:55

    My new favorite form (ES2015)

    Array(10).fill(1).map((x, y) => x + y)
    

    And if you need a function with a step param:

    const range = (start, stop, step = 1) =>
      Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)
    

提交回复
热议问题