JavaScript function similar to Python range()

前端 未结 24 1602
南旧
南旧 2020-11-30 21:17

Is there a function in JavaScript similar to Python\'s range()?

I think there should be a better way than to write the following lines every time:

24条回答
  •  渐次进展
    2020-11-30 21:44

    Still no built-in function that is equivalent to range(), but with the most recent version - ES2015 - you can build your own implementation. Here's a limited version of it. Limited because it doesn't take into account the step parameter. Just min, max.

    const range = (min = null, max = null) =>
      Array.from({length:max ? max - min : min}, (v,k) => max ? k + min : k)
    

    This is accomplished by the Array.from method able to build an array from any object that has a length property. So passing in a simple object with just the length property will create an ArrayIterator that will yield length number of objects.

提交回复
热议问题