我正在寻找以下方法的任何替代方法,以创建包含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])

其他回答

在ES6中:

Array.from({length: 1000}, (_, i) => i).slice(1);

或者更好(没有额外的变量_,也没有额外的切片调用):

Array.from({length:1000}, Number.call, i => i + 1)

或者,如果您的列表少于256个结果,您可以使用Uint8Array来获得稍快的结果(或者,您可以根据列表的长度使用其他Uint列表,例如Uint16的最大值为65535,或Uint32的最大值4294967295等。不过,正式地说,这些类型的数组只是在ES6中添加的)。例如:

Uint8Array.from({length:10}, Number.call, i => i + 1)

ES5:

Array.apply(0, {length: 1000}).map(function(){return arguments[1]+1});

或者,在ES5中,对于map函数(类似于上面ES6中Array.from函数的第二个参数),可以使用Number.call

Array.apply(0,{length:1000}).map(Number.call,Number).slice(1)

或者,如果你在这里也反对.sslice,你可以执行上面的ES5等效操作(来自ES6),比如:

Array.apply(0,{length:1000}).map(Number.call, Function("i","return i+1"))

试试这个

[…Array.from({length:30}).keys()]

填充Array的新方法是:

const array=[…array(5).keys()]console.log(数组)

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

基于高票答案和高票评论。

const range = (from, to) => [...Array(to + 1).keys()].slice(from);

// usage
let test = [];
test = range(5, 10);
console.log(test); // output: [ 5, 6, 7, 8, 9, 10 ]

//不分配N大小数组(ES6,带有一些流注释)的解决方案:函数*zeroToN(N/*:数字*/)/*:生成器<number,void,empty>*/{对于(设n=0;n<=n;n+=1),得到n;}//通过这一代,您可以拥有您的阵列console.log([…zeroToN(10-1)])//但是让我们定义一个助手迭代器函数函数mapIterator(迭代器,映射){常量arr=[];for(let result=iterater.next()!result.done;result=iterator.next()){arr.push(映射(result.value));}返回arr;}//现在您有了一个map函数,不需要分配0…N-1数组console.log(mapIterator(zeroToN(10-1),n=>n*n));