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

var foo = [];

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

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


当前回答

由于有很多好的答案,这可能也是一个选项,您也可以使用下面的创建一个函数,它将适用于任何数字组合

const start = 10;
const end = 30;    
const difference = Math.abs(start-end);
const rangeArray = new Array(difference + 1).fill(undefined).map((val, key) => {
    return start > end ? start - key : start + key;
})

其他回答

Fast

这个解决方案可能是最快的——它是由lodash_.range函数启发而来的(但我的更简单、更快)

设N=10,i=0,a=阵列(N);而(i<N)a[i++]=i;控制台日志(a);

与当前(2020.12.11)相比,基于while/for的现有答案的性能优势

内存在开始时由a=数组(N)分配一次使用了增加索引i++——看起来比减少索引i快30%左右——(可能是因为CPU缓存在正向上更快)

在此答案中,使用了20多种其他解决方案进行了速度测试

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

注意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-N

const[,…result]=数组(11).keys();console.log('结果:',结果);

数组固有地管理其长度。当它们被遍历时,它们的索引可以保存在内存中并在此时被引用。如果需要知道随机索引,可以使用indexOf方法。

也就是说,为了满足您的需要,您可能只需要声明一个特定大小的数组:

var foo = new Array(N);   // where N is a positive integer

/* this will create an array of size, N, primarily for memory allocation, 
   but does not create any defined values

   foo.length                                // size of Array
   foo[ Math.floor(foo.length/2) ] = 'value' // places value in the middle of the array
*/

ES6

传播

使用扩展运算符(…)和键方法,可以创建一个大小为N的临时数组来生成索引,然后创建一个可以分配给变量的新数组:

var foo = [ ...Array(N).keys() ];

填充/贴图

您可以首先创建所需数组的大小,用undefined填充它,然后使用map创建一个新数组,它将每个元素设置为索引。

var foo = Array(N).fill().map((v,i)=>i);

排列自

这应该是初始化到大小为N的长度,并一次填充数组。

Array.from({ length: N }, (v, i) => i)

代替注释和混淆,如果您真的想在上面的示例中获取1..N中的值,有几个选项:

如果索引可用,您可以简单地将其递增一(例如,++i)。在不使用索引的情况下——可能是一种更有效的方法——创建数组,但使N表示N+1,然后从前面移动。所以,如果你想要100个数字:let arr;(arr=[…数组(101).keys()]).shift()




对于小范围,切片是不错的。N仅在运行时已知,因此:

[0, 1, 2, 3, 4, 5].slice(0, N+1)