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

var foo = [];

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

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


当前回答

✅ 简单地说,这对我有用:

[...Array(5)].map(...)

其他回答

尝试在Number的原型中添加迭代器。

Number.prototype[Symbol.iterator] = function *(){
  let i = 0;
  while(i < this) yield i++;
  return;
}

现在数字是可迭代的,只需将一个数字传递给Array.from

Array.from(10);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

或者任何其他需要迭代的地方,比如。。。循环。

for(const number of 10) console.log(number);//logs 0 through 9 sequentially

这有点复杂,但也很酷。

让我们分享我的:p

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

如果您碰巧像我一样在应用程序中使用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]

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

使用ES6,您可以做到:

// `n` is the size you want to initialize your array
// `null` is what the array will be filled with (can be any other value)
Array(n).fill(null)

可以使用Int8Array、Int16Array和Int32Array创建范围从1到n的数组,如下所示:

const zeroTo100 = new Int8Array(100).map((curr, index) => curr = index + 1);
/* Int8Array(100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 
55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 
93, 94, 95, 96, 97, 98, 99, 100]

还可以使用以下类型化数组在数组中生成1到n个项。

Uint8Array、Uint16Array和Uint32ArrayBigInt64阵列Uint8约束阵列浮置阵列32、浮置阵列64

当然,除了数字之外,您无法在这些数组中放置任何东西,所以使用这个小快捷方式会带来风险。

此外,如果您只需要一个包含n个零的数组,那么只需执行以下操作:

const arr_100_0s = new Int8Array(100)

编辑:您可以使用它快速生成范围,如下所示:

function range(start, end) {
    const arr = new Int8Array(end - start + 1).map((curr, i) => curr + i + start);
    return arr;
}

range(15, 30); // Int8Array(16) [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

不完全符合用户的要求,但与IMO高度相关。