最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript one liner range array - Stack Overflow

programmeradmin2浏览0评论

Is there a nice one liner for a range array in javascript, equivalent to python's list(range(m, n))? ES6 permitted. Here's the best I've e up with so far:

[x for(x of (function*(){for(let i=0;i<100;i++) yield i})())]

Is there a nice one liner for a range array in javascript, equivalent to python's list(range(m, n))? ES6 permitted. Here's the best I've e up with so far:

[x for(x of (function*(){for(let i=0;i<100;i++) yield i})())]
Share Improve this question asked Oct 15, 2014 at 14:27 simonzacksimonzack 21k14 gold badges81 silver badges124 bronze badges 5
  • possible duplicate of Create a JavaScript array containing 1...N – antyrat Commented Oct 15, 2014 at 14:29
  • @antyrat slightly different, this one's m..n. Not all answers there are applicable. – simonzack Commented Oct 15, 2014 at 14:30
  • 1 Just create a function like CreateRange(5, 10). Any trick one line solution I can think of is not very readable in JS. – David Sherret Commented Oct 15, 2014 at 14:35
  • @DavidSherret I'm indeed after readability, I could just use underscore's range otherwise. – simonzack Commented Oct 15, 2014 at 14:42
  • I agree with @DavidSherret, there's no good one line. The closest would be Array.from({length:10-5}, (v,k) => k + 5) but I don't find it to be terribly succint. Why does it have to be one line btw? – CervEd Commented Oct 23, 2016 at 0:03
Add a ment  | 

2 Answers 2

Reset to default 9

You can use Array.from and arrow functions for a better readability:

Array.from({length: 4}, (_, n) => n) // = [0, 1, 2, 3]
Array.from({length: 5}, (_, n) => n+6) // = [6, 7, 8, 9, 10]
Array.from({length: 6}, (_, n) => n-3) // = [-3, -2, -1, 0, 1, 2]

You can just do this

var arr = [];  while(arr[arr.length-1] !== end) arr.push(start++); // one-liner

Making the above to a function will result in

function createRange(start, end) {
   var arr = [];  while(arr[arr.length-1] !== end) arr.push(start++); // one-liner
   return arr;
}
发布评论

评论列表(0)

  1. 暂无评论