JavaScript function similar to Python range()

前端 未结 24 1611
南旧
南旧 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:33

    2018: this answer keeps getting upvotes, so here's an update. The code below is obsolete, but luckily ES6 standardized generators and the yield keyword, and they are universally supported across platforms. An example of the lazy range() using yield can be found here.


    In addition to what's already said, Javascript 1.7+ provides support for iterators and generators which can be used to create a lazy, memory-efficient version of range, simlar to xrange in Python2:

    function range(low, high) {  
        return {
            __iterator__: function() {
                return {  
                    next: function() {
                        if (low > high)
                            throw StopIteration;  
                        return low++;
                    }
                }
            }
        }
    }
    
    for (var i in range(3, 5))  
      console.log(i); // 3,4,5
    

提交回复
热议问题