Languages

JavaScript - create array from for loop

0 points
Asked by:
Imaan-Morin
1009

I have a range stored into two variables and I want to create an array within the range.

Something like this:

What should I put inside the object to make it work?

The result I'd like to get would be:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

ES6+ solution

You can use Array() constructor to create array, then fill() and map() methods to fill the array with the values in range:

Solution for older versions

This solution uses a simple while loop to push values in range inside the array.

 

References

  1. Array() constructor - JavaScript | MDN
  2. Array.prototype.fill() - JavaScript | MDN
  3. Array.prototype.map() - JavaScript | MDN
  4. while - JavaScript | MDN
  5. Array.prototype.push() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join