JavaScript function similar to Python range()

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

    An option for NodeJs is to use a Buffer:

    [...Buffer.alloc(5).keys()]
    // [ 0, 1, 2, 3, 4 ]
    

    What's nice is that you can iterate directly on the buffer:

    Buffer.alloc(5).forEach((_, index) => console.log(index))
    // 0
    // 1
    // 2
    // 3
    // 4
    

    You can't do that with an uninitialized Array:

    Array(5).forEach((_, index) => console.log(index))
    // undefined
    

    But, who in their right mind uses a Buffer for a purpose like this ;)

提交回复
热议问题