How to generate sequence of numbers/chars in javascript?

How to generate sequence of numbers/chars in javascript?

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, but wondering whether there is a jQuery library or javascript function that can do it for me?


Solution 1:

You can make your own re-usable function I suppose, for your example:

function makeArray(count, content) {
   var result = [];
   if(typeof content == "function") {
      for(var i = 0; i < count; i++) {
   } else {
      for(var i = 0; i < count; i++) {
   return result;

Then you could do either of these:

var myArray = makeArray(8, 1);
//or something more complex, for example:
var myArray = makeArray(8, function(i) { return i * 3; });

You can give it a try here, note the above example doesn’t rely on jQuery at all so you can use it without. You just don’t gain anything from the library for something like this 🙂

Solution 2:

Without a for loop, here is a solution:

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

The explanation follows.

Related:  Best practices of building a website using Node.js

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.

Solution 3:

for (var i=8, a=[]; i--;) a.push(1);

Solution 4:

Using Jquery:

$.map($(Array(8)),function(val, i) { return i; })

This returns:

[0, 1, 2, 3, 4, 5, 6, 7]

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

This returns:

[1, 1, 1, 1, 1, 1, 1, 1]

Solution 5:

In case you are using newer Javascript syntax, the same can be achieved using:


The following works fine too but as Matt pointed out, the keyword ‘new’ is redundant.

new Array(8).fill(1)

Solution 6:

2016 – Modern Browser functionality has arrived. No need for jquery all the time.

Array.from({length: 8}, (el, index) => 1 /* or index */);

You can substitute the arrow function with a simple callback function to reach a slightly wider range of supported browsers. It’s, for me at least, the easiest way to iterate over an initialized array in one step.

Related:  JavaScript equality transitivity is weird

Note: IE is not supported in this solution, but there is a polyfill for that at…