JavaScript function similar to Python range()

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

    function range(start, stop) {
        if (typeof stop == 'undefined') {
            stop = start;
            start = 0;
        }
       
        result = [...Array(stop).keys()].slice(start, stop);
        return result;
    }
    

提交回复
热议问题