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

var foo = [];

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

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


当前回答

让我们分享我的:p

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

其他回答

只是另一个ES6版本。

通过使用Array.from第二个可选参数:

Array.from(arrayLike[,mapFn[,thisArg]])

我们可以从空数组(10)位置构建编号数组:

Array.from(Array(10), (_, i) => i)

var arr=数组.来自(数组(10),(_,i)=>i);文档.写入(arr);

Array.prototype.fill()

a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)

[0, 1, 2, 3, 4, 5, 6]

您可以使用此选项:

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]

获取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)})
}

在ES6中,您可以执行以下操作:

数组(N).fill().map((e,i)=>i+1);

http://jsbin.com/molabiluwa/edit?js安慰

编辑:更新问题后,将数组(45)更改为数组(N)。

控制台日志(数组(45).填充(0).映射((e,i)=>i+1));