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

var foo = [];

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

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


当前回答

如果您碰巧像我一样在应用程序中使用d3.js,d3会提供一个助手函数来为您执行此操作。

因此,要获得从0到4的数组,非常简单:

d3.range(5)
[0, 1, 2, 3, 4]

并获得从1到5的数组,如您所请求的:

d3.range(1, 5+1)
[1, 2, 3, 4, 5]

查看本教程了解更多信息。

其他回答

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

/**
 * 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]

让我们分享我的:p

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

Array.prototype.fill()

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

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

我能想出的最简洁的办法是:

[...''.padEnd(N)].map((_,i)=>i+1)