JavaScript function similar to Python range()

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

    Here is another es6 implementation of the range

    // range :: (from, to, step?) -> [Number]
    const range = (from, to, step = 1) => {
      //swap values if necesery
      [from, to] = from > to ? [to, from] : [from, to]
      //create range array
      return [...Array(Math.round((to - from) / step))]
        .map((_, index) => {
          const negative = from < 0 ? Math.abs(from) : 0
          return index < negative ? 
            from + index * step  :
            (index - negative + 1) * step
        })
    }  
    
    range(-20, 0, 5)
      .forEach(val => console.log(val))
    
    for(const val of range(5, 1)){
       console.log(`value ${val}`)
    }

提交回复
热议问题