JavaScript function similar to Python range()

前端 未结 24 1606
南旧
南旧 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条回答
  •  Happy的楠姐
    2020-11-30 21:39

    Can be achieved by attaching an iterator to the Number prototype

      Number.prototype[Symbol.iterator] = function* () { 
         for (var i = 0; i <= this; i++) {
           yield i
         } 
      }
    
    [...5] // will result in [0,1,2,3,4,5]
    

    Taken from Kyle Simpson's course Rethinking Asynchronous JavaScript

提交回复
热议问题