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

var foo = [];

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

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


当前回答

似乎目前唯一没有出现在这个相当完整的答案列表中的味道是一个生成器;以便补救:

const gen = N => [...(function*(){let i=0;while(i<N)yield i++})()]

其可以这样使用:

gen(4) // [0,1,2,3]

这件事的好处是你不需要增加。。。要从@igor shubin给出的答案中获得灵感,您可以非常容易地创建一系列随机数:

const gen = N => [...(function*(){let i=0;
  while(i++<N) yield Math.random()
})()]

而不是像这样的冗长的运营成本高昂的事情:

const slow = N => new Array(N).join().split(',').map((e,i)=>i*5)
// [0,5,10,15,...]

您可以改为:

const fast = N => [...(function*(){let i=0;while(i++<N)yield i*5})()]

其他回答

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

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

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

为了好玩,我想借鉴伊恩·亨利的答案。

当然,var array=new array(N);将为您提供大小为N的数组,但键和值将相同。。。。然后,要将数组缩短为M大小,请使用array.length=M…但对于一些添加的功能,请尝试:

function range()
{
    // This function takes optional arguments:
    // start, end, increment
    //    start may be larger or smaller than end
    // Example:  range(null, null, 2);

    var array = []; // Create empty array

      // Get arguments or set default values:
    var start = (arguments[0] ? arguments[0] : 0);
    var end   = (arguments[1] ? arguments[1] : 9);
      // If start == end return array of size 1
    if (start == end) { array.push(start); return array; }
    var inc   = (arguments[2] ? Math.abs(arguments[2]) : 1);

    inc *= (start > end ? -1 : 1); // Figure out which direction to increment.

      // Loop ending condition depends on relative sizes of start and end
    for (var i = start; (start < end ? i <= end : i >= end) ; i += inc)
        array.push(i);

    return array;
}

var foo = range(1, -100, 8.5)

for(var i=0;i<foo.length;i++){
  document.write(foo[i] + ' is item: ' + (i+1) + ' of ' + foo.length + '<br/>'); 
}​

上述输出:

1是第1项,共12项-7.5为第2项,共12项-16是第3项,共12项-24.5为第4项,共12项-33是第5项,共12项-41.5是第6项,共12项-50是第7项,共12项-58.5为第8项,共12项-67是第9项,共12项-75.5为第10项,共12项-84是第11项,共12项-92.5是第12项,共12项

jsFiddle示例

此函数使用自动生成的参数数组。

该函数创建一个数组,该数组中的值以大小增量开始,以大小增量结束,其中

range(start, end, increment);

每个值都有一个默认值,增量的符号无关紧要,因为增量的方向取决于开始和结束的相对大小。

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




https://stackoverflow.com/a/49577331/8784402

使用Delta

对于javascript

smallest and one-liner
[...Array(N)].map((v, i) => from + i * step);

示例和其他备选方案

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((v, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

[...Array(10)].map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Range Function
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

带步长/增量的从到

using iterators
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

对于字体

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);