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

var foo = [];

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

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


当前回答

//不分配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));

其他回答

嗯,简单但重要的问题。Functional JS在Array对象下肯定缺少一个通用的展开方法,因为我们可能需要创建一个数字项数组,不仅是简单的[1,2,3,…,111],而且是一个函数产生的序列,可能是x=>x*2而不是x=>x

目前,要执行这项工作,我们必须依赖Array.prototype.map()方法。然而,为了使用Array.prototype.map(),我们需要提前知道数组的大小。还是。。如果我们不知道大小,那么我们可以使用Array.prototype.reduce(),但Array.protocol.reduce)用于缩小(折叠)而不是展开正确。。?

显然,我们需要函数JS中的Array.unfold()工具。这是我们可以简单地自己实现的;

Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};

数组展开(p,f,t,v)采用4个参数。

p这是一个定义停止位置的函数。与许多数组函子一样,p函数接受3个参数。值、索引和当前生成的数组。它应返回布尔值。当它返回true时,递归迭代停止。f这是一个返回下一项函数值的函数。t这是一个函数,用于返回下一个参数,以便在下一个回合中提供给f。s是种子值,用于通过f计算索引0的舒适座椅。

因此,如果我们打算创建一个数组,其中包含一个像1,4,9,16,25…n^2这样的序列,我们可以简单地这样做。

Array.unfold=函数(p,f,t,s){var res=[],转轮=v=>p(v,res.length-1,res)?[]:(res.push(f(v)),runner(t(v),res);回流流道;};var myArr=数组展开((_,i)=>i>=9,x=>Math.pow(x,2),x=>x+1,1);console.log(myArr);

在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"))

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

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

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


console.log(range(5));

不支持在ES6解决方案中创建阵列

js不适用于100阵列

1.焊盘启动


// string arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]


// number arr
const arr = [...``.padStart(100, ` `)].map((item, i) => i + 1);

// (100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]


2.类型化阵列

Uint8阵列

// number arr
const arr = new Uint8Array(100).map((item, i) => i + 1);

// Uint8Array(100) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

// string arr
const arr = [...new Uint8Array(100).map((item, i) => i + 1)].map((item, i) => i + 1 + ``);

// (100) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]