How to generate sequence of numbers/chars in javascript?

前端 未结 18 1196
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 06:22

Is there a way to generate sequence of characters or numbers in javascript?

For example, I want to create array that contains eight 1s. I can do it with for loop, bu

18条回答
  •  借酒劲吻你
    2020-12-13 06:40

    The original question was edited. So the updated example answers:

    To fill the same content:

    Array(8).fill(1)
    //=> [1, 1, 1, 1, 1, 1, 1, 1]
    

    To fill sequential numbers, starting from 5:

    Array(8).fill().map((element, index) => index + 5)
    //=> [5, 6, 7, 8, 9, 10, 11, 12]
    

    To fill sequencial characters, starting from 'G':

    Array(8).fill().map((element, index) => String.fromCharCode('G'.charCodeAt(0) + index)) 
    //=> ["G", "H", "I", "J", "K", "L", "M", "N"]
    

提交回复
热议问题