我正在寻找以下方法的任何替代方法,以创建包含1到N的JavaScript数组,其中N仅在运行时已知。

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

对我来说,我觉得应该有一种不用循环的方法。


当前回答

Array.prototype.fill()

a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)

[0, 1, 2, 3, 4, 5, 6]

其他回答

基于高票答案和高票评论。

const range = (from, to) => [...Array(to + 1).keys()].slice(from);

// usage
let test = [];
test = range(5, 10);
console.log(test); // output: [ 5, 6, 7, 8, 9, 10 ]

我能产生的最少代码:

for(foo=[x=100]; x; foo[x-1]=x--);
console.log(foo);

让我们分享我的:p

Math.pow(2, 10).toString(2).split('').slice(1).map((_,j) => ++j)

我没有看到任何基于递归函数的解决方案(我自己也从未编写过递归函数),所以这里是我的尝试。

注意array.push(something)返回数组的新长度:

(a=[]).push(a.push(a.push(0))) //  a = [0, 1, 2]

使用递归函数:

var a = (function f(s,e,a,n){return ((n?n:n=s)>e)?a:f(s,e,a?a:a=[],a.push(n)+s)})(start,end) // e.g., start = 1, end = 5

编辑:其他两种解决方案

var a = Object.keys(new Int8Array(6)).map(Number).slice(1)

and

var a = []
var i=setInterval(function(){a.length===5?clearInterval(i):a.push(a.length+1)}) 

有一个小功能,它允许使用像[1,2]。范围(3,4)->[1,2,3,4]也适用于负参数。享受

Array.prototype.range = function(from, to)
{
   var range = (!to)? from : Math.abs(to - from) + 1, increase = from < to;
   var tmp = Array.apply(this, {"length": range}).map(function()
      {
         return (increase)?from++ : from--;
      }, Number);

   return this.concat(tmp);
};