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

var foo = [];

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

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


当前回答

您可以使用此选项:

new Array(/*any number which you want*/)
    .join().split(',')
    .map(function(item, index){ return ++index;})

例如

new Array(10)
    .join().split(',')
    .map(function(item, index){ return ++index;})

将创建以下数组:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

其他回答

您可以使用Es6中的阵列填充和映射;就像一些人在回答这个问题时建议的那样。以下是一些示例:

Example-One: Array(10).fill(0).map((e,i)=>i+1)

Result-One: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example-Two: Array(100/10).fill(0).map((e,i)=>(i*10)+10)

Result-Two:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

我更喜欢这样,因为我觉得这很简单。

有一个小功能,它允许使用像[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);
};

似乎目前唯一没有出现在这个相当完整的答案列表中的味道是一个生成器;以便补救:

const gen = N => [...(function*(){let i=0;while(i<N)yield i++})()]

其可以这样使用:

gen(4) // [0,1,2,3]

这件事的好处是你不需要增加。。。要从@igor shubin给出的答案中获得灵感,您可以非常容易地创建一系列随机数:

const gen = N => [...(function*(){let i=0;
  while(i++<N) yield Math.random()
})()]

而不是像这样的冗长的运营成本高昂的事情:

const slow = N => new Array(N).join().split(',').map((e,i)=>i*5)
// [0,5,10,15,...]

您可以改为:

const fast = N => [...(function*(){let i=0;while(i++<N)yield i*5})()]

Array.prototype.fill()

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

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

以下函数返回一个由数字填充的数组:

var createArrayOfNumbers = function (n) {
    return Array.apply(null, new Array(n)).map(function (empty, index) {
        return index;
    });
};

请注意,使用数组构造函数创建的数组由孔组成,因此不能使用map等数组函数遍历。因此使用Array.apply函数。