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

var foo = [];

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

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


当前回答

感谢@NikoRuotsalainen的回答。我在我的实用程序中写道:

const range = ({from = 0, to, step = 1, length = Math.ceil((to - from) / step)}) => 
  Array.from({length}, (_, i) => from + i * step)

示例:常量范围=({from=0,to,step=1,length=Math.ceil((to-from)/step)})=>Array.from({length},(_,i)=>from+i*step)控制台日志(范围({长度:5}),//[0,1,2,3,4]范围({到:5}),//[0,1,2,3,4]范围({从:2,到:5}),//[2,3,4](包括“从”,不包括“到”)范围({从:2,长度:4}),//[2,3,4,5]范围({从:1到:5,步骤:2}),//[1,3]范围({从:1到:6,步骤:2}),//[1,3,5])

其他回答

数组固有地管理其长度。当它们被遍历时,它们的索引可以保存在内存中并在此时被引用。如果需要知道随机索引,可以使用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()




使用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)

使用递归的ES6解决方案。不同于所有其他解决方案

const range = (n, A = []) => (n === 1) ? [n, ...A] : range(n - 1, [n, ...A]);


console.log(range(5));

感谢@NikoRuotsalainen的回答。我在我的实用程序中写道:

const range = ({from = 0, to, step = 1, length = Math.ceil((to - from) / step)}) => 
  Array.from({length}, (_, i) => from + i * step)

示例:常量范围=({from=0,to,step=1,length=Math.ceil((to-from)/step)})=>Array.from({length},(_,i)=>from+i*step)控制台日志(范围({长度:5}),//[0,1,2,3,4]范围({到:5}),//[0,1,2,3,4]范围({从:2,到:5}),//[2,3,4](包括“从”,不包括“到”)范围({从:2,长度:4}),//[2,3,4,5]范围({从:1到:5,步骤:2}),//[1,3]范围({从:1到:6,步骤:2}),//[1,3,5])

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

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;
})