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

var foo = [];

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

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


当前回答

获取n个介于最小值和最大值之间的随机数的数组(虽然不是唯一的)

function callItWhatYouWant(n, min, max) {
    return Array.apply(null, {length: n}).map(Function.call, function(){return Math.floor(Math.random()*(max-min+1)+min)})
}

其他回答

填充Array的新方法是:

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

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

for(var i,a=[i=0];i<10;a[i++]=i);

a=[1、2、3、4、5、6、7、8、9、10]

使用非常流行的Undercore_.range方法

// _.range([start], stop, [step])

_.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0); // => []

您可以使用此选项:

new Array(/*any number which you want*/)
    .join().split(',')
    .map(function(item, index){ return ++index;})

例如

new Array(10)
    .join().split(',')
    .map(function(item, index){ return ++index;})

将创建以下数组:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

让我们分享我的:p

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