Is there a function in JavaScript similar to Python’s range()
?
I think there should be a better way than to write the following lines every time:
JavaScript
x
5
1
array = new Array();
2
for (i = 0; i < specified_len; i++) {
3
array[i] = i;
4
}
5
Advertisement
Answer
No, there is none, but you can make one.
JavaScript’s implementation of Python’s range()
Trying to emulate how it works in Python, I would create function similar to this:
JavaScript
1
23
23
1
function range(start, stop, step) {
2
if (typeof stop == 'undefined') {
3
// one param defined
4
stop = start;
5
start = 0;
6
}
7
8
if (typeof step == 'undefined') {
9
step = 1;
10
}
11
12
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
13
return [];
14
}
15
16
var result = [];
17
for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
18
result.push(i);
19
}
20
21
return result;
22
};
23
See this jsfiddle for a proof.
Comparison between range()
in JavaScript and Python
It works in the following way:
range(4)
returns[0, 1, 2, 3]
,range(3,6)
returns[3, 4, 5]
,range(0,10,2)
returns[0, 2, 4, 6, 8]
,range(10,0,-1)
returns[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
,range(8,2,-2)
returns[8, 6, 4]
,range(8,2)
returns[]
,range(8,2,2)
returns[]
,range(1,5,-1)
returns[]
,range(1,5,-2)
returns[]
,
and its Python counterpart works exactly the same way (at least in the mentioned cases):
JavaScript
1
19
19
1
>>> range(4)
2
[0, 1, 2, 3]
3
>>> range(3,6)
4
[3, 4, 5]
5
>>> range(0,10,2)
6
[0, 2, 4, 6, 8]
7
>>> range(10,0,-1)
8
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
9
>>> range(8,2,-2)
10
[8, 6, 4]
11
>>> range(8,2)
12
[]
13
>>> range(8,2,2)
14
[]
15
>>> range(1,5,-1)
16
[]
17
>>> range(1,5,-2)
18
[]
19
So if you need a function to work similarly to Python’s range()
, you can use above mentioned solution.