Categories
JavaScript Answers

How to Generate a Sequence of Numbers or Characters in JavaScript?

Spread the love

Sometimes, we want to generate a sequence of numbers or characters in JavaScript.

In this article, we’ll look at how to generate a sequence of numbers or characters in JavaScript.

Generate a Sequence of Numbers or Characters in JavaScript

To generate a sequence of numbers or characters in JavaScript, we can create our own function.

For instance, we write:

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

const arr1 = makeArray(8, 1);
console.log(arr1)

const arr2 = makeArray(8, (i) => {
  return i * 3;
});
console.log(arr2)

We create the makeArray function that takes the count and content parameters.

count has the number of entries in the array.

content has the content we want to add, which can be generated from a function or any value.

In the function, we initialize result to an empty array.

Then we check if content is a function with typeof .

If it is, then we use a for loop to push the entries returned by content to result .

Otherwise, we push content into result directly with another for loop.

Therefore, arr1 is [1, 1, 1, 1, 1, 1, 1, 1] .

And arr2 is [0, 3, 6, 9, 12, 15, 18, 21] .

Conclusion

To generate a sequence of numbers or characters in JavaScript, we can create our own function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *