1

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.

3 Answers3

2

You can try this code instead, but you need to create a function first:

var number_array = [];

function range(start,stop) {
    for (i =start; i < (stop+1); i++) {
        number_array.push(i);
    }
    return number_array;
}
ross
  • 2,684
  • 2
  • 13
  • 22
alecneil
  • 36
  • 2
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
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