JavaScript function similar to Python range()

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

    MDN recommends this approach: Sequence generator (range)

    // Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
    const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
    
    // Generate numbers range 0..4
    console.log("range(0, 4, 1):", range(0, 4, 1));
    // [0, 1, 2, 3, 4] 
    
    // Generate numbers range 1..10 with step of 2 
    console.log("\nrange(1, 10, 2):", range(1, 10, 2));
    // [1, 3, 5, 7, 9]
    
    // Generate the alphabet using Array.from making use of it being ordered as a sequence
    console.log("\nrange('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x))", range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x)));
    // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

提交回复
热议问题