Skip to main content
edited body
Source Link
Jonas Wilms
  • 139.3k
  • 20
  • 164
  • 164
 const range = (start, end) => Array.from({length: end - start}, (_, i) => start + i); console.log(range(1,5)); 

That creates an array with the indexes. If you need it in a loop, an iterator might be better:

 function* range(start, end = Infinity) { for(let i = start; i < end; i++) yield i; } 

Which can be used as:

 for(const v of range(1, 10)) console.log(v); 

You can also turn an iterator into an array essilyeasily:

 console.log([...range(0, 10)]); 
 const range = (start, end) => Array.from({length: end - start}, (_, i) => start + i); console.log(range(1,5)); 

That creates an array with the indexes. If you need it in a loop, an iterator might be better:

 function* range(start, end = Infinity) { for(let i = start; i < end; i++) yield i; } 

Which can be used as:

 for(const v of range(1, 10)) console.log(v); 

You can also turn an iterator into an array essily:

 console.log([...range(0, 10)]); 
 const range = (start, end) => Array.from({length: end - start}, (_, i) => start + i); console.log(range(1,5)); 

That creates an array with the indexes. If you need it in a loop, an iterator might be better:

 function* range(start, end = Infinity) { for(let i = start; i < end; i++) yield i; } 

Which can be used as:

 for(const v of range(1, 10)) console.log(v); 

You can also turn an iterator into an array easily:

 console.log([...range(0, 10)]); 
Source Link
Jonas Wilms
  • 139.3k
  • 20
  • 164
  • 164

 const range = (start, end) => Array.from({length: end - start}, (_, i) => start + i); console.log(range(1,5)); 

That creates an array with the indexes. If you need it in a loop, an iterator might be better:

 function* range(start, end = Infinity) { for(let i = start; i < end; i++) yield i; } 

Which can be used as:

 for(const v of range(1, 10)) console.log(v); 

You can also turn an iterator into an array essily:

 console.log([...range(0, 10)]);