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

var foo = [];

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

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


当前回答

问题是这个技术的替代方案,但我想分享更快的方法。它与问题中的代码几乎相同,但它分配内存而不是使用push:

function range(n) {
    let a = Array(n);
    for (let i = 0; i < n; a[i++] = i);
    return a;
}

其他回答

我能产生的最少代码:

for(foo=[x=100]; x; foo[x-1]=x--);
console.log(foo);
Array(8).fill(0).map(Number.call, Number)

偷取Igors数字。可以使用技巧,但使用fill()稍微缩短。仅适用于ES6及以上版本。

对我来说,这是更有用的实用程序:

/**
 * create an array filled with integer numbers from base to length
 * @param {number} from
 * @param {number} to
 * @param {number} increment
 * @param {Array} exclude
 * @return {Array}
 */
export const count = (from = 0, to = 1, increment = 1, exclude = []) => {
  const array = [];
  for (let i = from; i <= to; i += increment) !exclude.includes(i) && array.push(i);
  return array;
};

在v8中填充数组的最快方法是:

[...Array(5)].map((_,i) => i);

结果将为:[0,1,2,3,4]

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