JavaScript function similar to Python range()

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

    No, there is none, but you can make one.

    I'm partial to Python3 behavior of range. You will find below JavaScript's implementation of Python's range():

    function* range(start=0, end=undefined, step=1) {    
        if(arguments.length === 1) {end = start, start = 0}    
        
        [...arguments].forEach(arg => {    
            if( typeof arg !== 'number') {throw new TypeError("Invalid argument")}                               
        })    
        if(arguments.length === 0) {throw new TypeError("More arguments neede")}    
            
        if(start >= end) return                                                                                                                                     
        yield start    
        yield* range(start + step, end, step)    
    }    
             
    // Use Cases
    console.log([...range(5)])
    
    console.log([...range(2, 5)])
    
    console.log([...range(2, 5, 2)])
    console.log([...range(2,3)])
    // You can, of course, iterate through the range instance.

提交回复
热议问题