How to generate sequence of numbers/chars in javascript?

前端 未结 18 1188
被撕碎了的回忆
被撕碎了的回忆 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:57

    Without a for loop, here is a solution:

    Array.apply(0, Array(8)).map(function() { return 1; })
    

    The explanation follows.

    Array(8) produces a sparse array with 8 elements, all undefined. The apply trick will turn it into a dense array. Finally, with map, we replace that undefined the (same) value of 1.

提交回复
热议问题