JavaScript function similar to Python range()

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

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

    As answered before: no, there's not. But you can make your own. I believe this is an interesting approach for ES6. It works very similar to Python 2.7 range(), but it's much more dynamic.

    function range(start, stop, step = 1) 
    {
        // This will make the function behave as range(stop)
        if(arguments.length === 1)
        {
            return [...Array(arguments[0]).keys()]
        }
    
        // Adjusts step to go towards the stop value
        if((start > stop && !(step < 0)) ||
           (start < stop && !(step > 0)))
        {
            step *= -1
        }
    
        let returnArray = []
        // Checks if i is in the interval between start and stop no matter if stop
        // is lower than start or vice-versa
        for(let i = start; (i-start)*(i-stop) <= 0; i += step)
        {
            returnArray.push(i)
        }
        return returnArray
    }
    

    This function can behave in three different ways (just like Python's range()):

    1. range(stop)
    2. range(start, stop)
    3. range(start, stop, step)

    These examples:

    console.log(range(5))
    console.log(range(-2, 2))
    console.log(range(2, -2))
    console.log(range(10, 20, 2))
    

    Will give you the following output:

    [ 0, 1, 2, 3, 4 ]
    [ -2, -1, 0, 1, 2 ]
    [ 2, 1, 0, -1, -2 ]
    [ 10, 12, 14, 16, 18, 20 ]
    

    Note that instead of iterating over the array with the in operator (like python), you have to use of. Thus the i variable assumes the value, and not the index, of the array's element.

    for(let i of range(5))
    {
        // do something with i...
    }
    

提交回复
热议问题