Last Updated: November 19, 2020
·
2.15K
· alvarogarcia7

Javascript range / list comprehensions

I was looking how to use a python-equivalent range function. The closest I found is

Array.apply(null, Array(16)).map(
   function (_, i) {
       return i;
    }   
);

//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Source: http://stackoverflow.com/questions/3895478/does-javascript-have-a-range-equivalent

That can also help you create list comprehensions:

Array.apply(null, Array(16)).map(
   function (_, i) {
       var root = i+1;
       var squared = root * root;
       return squared;
    }   
);

//[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]

Related protips:

Flatten a list of lists in one line in Python

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside