I want to know what is the equivalent code for the python's range(start,stop,step=1). If anyone knows, I am really grateful for the help.
Asked
Active
Viewed 693 times
1
-
a for loop. Please show your research. – Sayse Aug 13 '19 at 14:44
3 Answers
2
JavaScript doesn't have a range method. Please refer to the Looping Code section in MDN's JavaScript guide for further info.
Also, try doing some research or giving examples of what you'd like to achieve before asking such questions. A code is sample or a simple description would be sufficient.

rici
- 234,347
- 28
- 237
- 341

Emmanuel Gabriel
- 97
- 2
- 10
0
The lazily evaluated version of range()
; what used to be xrange()
;
function* range(start, end, step) {
const numArgs = arguments.length;
if (numArgs < 1) start = 0;
if (numArgs < 2) end = start, start = 0;
if (numArgs < 3) step = end < start ? -1 : 1;
// ignore the sign of the step
//const n = Math.abs((end-start) / step);
const n = (end - start) / step;
if (!isFinite(n)) return;
for (let i = 0; i < n; ++i)
yield start + i * step;
}
console.log("optional arguments:", ...range(5));
console.log("and the other direction:", ...range(8, -8));
console.log("and with steps:", ...range(8, -8, -3));
for(let nr of range(5, -5, -2))
console.log("works with for..of:", nr);
console.log("and everywhere you can use iterators");
const [one, two, three, four] = range(1,4);
const obj = {one, two, three, four};
console.log(obj)
.as-console-wrapper{top:0;max-height:100%!important}

Thomas
- 11,958
- 1
- 14
- 23