Jak wygenerować zakres liczb od 0 do n tylko w ES2015?

Zawsze znajdowałem range Brak funkcji w JavaScript, ponieważ jest ona dostępna w Pythonie i innych? Czy jest jakiś zwięzły sposób na wygenerowanie zakresu liczb w ES2015 ?

EDIT: moje pytanie różni się od wspomnianego duplikatu, ponieważ jest specyficzne dla ES2015, a nie ECMASCRIPT-5. Również potrzebuję zakresu zaczynającego się od 0, a nie konkretnej liczby początkowej (chociaż byłoby dobrze, gdyby tak było)

Author: Aditya Singh, 2016-04-30

10 answers

Możesz użyć operatora spread na kluczach świeżo utworzonej tablicy.

[...Array(n).keys()]

Lub

Array.from(Array(n).keys())

Składnia Array.from() jest niezbędna w przypadku pracy z maszynopisem

 143
Author: Delapouite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 22:41:20

Znalazłem również jeden bardziej intuicyjny sposób za pomocą Array.from:

const range = n => Array.from({length: n}, (value, key) => key)

Teraz ta funkcja range zwróci wszystkie liczby od 0 do n-1

Zmodyfikowaną wersją zakresu do obsługi start i end jest:

const range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);

EDIT Jak zasugerował @ marco6, możesz umieścić to jako metodę statyczną, jeśli pasuje do twojego przypadku użycia

Array.range = (start, end) => Array.from({length: (end - start)}, (v, k) => k + start);

I użyj go jako

Array.range(3, 9)
 74
Author: Aditya Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-13 07:09:04

Z Deltą

Dla javascript

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, 2, 0, -2, -4, -6, -8, -10, -12, -14]

const range = (from, to, step) =>
  Array(~~((to - from) / step) + 1) // '~~' is Alternative for Math.floor()
  .fill().map((v, i) => from + i * step);

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

Array.range = (from, to, step) => Array.from({
    length: ~~((to - from) / step) + 1
  },
  (v, k) => from + k * step
);

Array.range = (from, to, step) => [...Array(~~((to - from) / step) + 1)].map(
  (v, k) => from + k * 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]


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

// Or
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

class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function*() {
      let i = 0,
        length = ~~((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]

// Or 
const Range2 = function*(to = 0, step = 1, from = 0) {
    let i = 0, length = ~~((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, 8);
even4to10.next().value
//=> 8
even4to10.next().value
//=> 10
even4to10.next().value
//=> undefined

Do Maszynopisu

interface _Iterable extends Iterable < {} > {
  length: number;
}

class _Array < T > extends Array < T > {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(
      ( < _Iterable > { length: Math.floor((to - from) / step) + 1 }),
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Update

class _Array<T> extends Array<T> {
    static range(from: number, to: number, step: number): number[] {
        return [...Array(~~((to - from) / step) + 1)].map(
            (v, k) => from + k * step
        );
    }
}
_Array.range(0, 9, 1);
 4
Author: nkitku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-30 18:50:05

Do obsługi delta

const range = (start, end, delta) => {
  return Array.from(
    {length: (end - start) / delta}, (v, k) => (k * delta) + start
  )
};
 2
Author: user3500066,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 02:01:54

Możesz również zrobić to z jedną wkładką z podparciem krokowym, takim jak Ta:

((from, to, step) => ((add, arr, v) => add(arr, v, add))((arr, v, add) => v < to ? add(arr.concat([v]), v + step, add) : arr, [], from))(0, 10, 1)

Wynikiem jest [0, 1, 2, 3, 4, 5, 6 ,7 ,8 ,9].

 1
Author: Marcin Król,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-13 13:05:27
const keys = Array(n).keys();
[...Array.from(keys)].forEach(callback);

In Typescript

 0
Author: PeiSong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-15 07:37:36

Oto kolejna odmiana, która nie używa Array.

let range = (n, l=[], delta=1) => {
  if (n < 0) { 
    return l 
  }
  else {
    l.unshift(n)
    return range(n - delta, l) 
  }
}
 0
Author: Han Lazarus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-24 18:42:58

Więc w tym przypadku byłoby miło, gdyby Number obiekt zachowywał się jak obiekt tablicy z operatorem spread.

Na przykład Tablica obiekt używany z operatorem spread:

let foo = [0,1,2,3];
console.log(...foo) // returns 0 1 2 3

Działa to tak, ponieważ obiekt Array ma wbudowany iterator.
W naszym przypadku potrzebujemy obiektu Numer , aby miał podobną funkcjonalność:

[...3] //should return [0,1,2,3]

W tym celu możemy po prostu utworzyć iterator liczb.

Number.prototype[Symbol.iterator] = function *() {
   for(let i = 0; i <= this; i++)
       yield i;
}

Teraz jest to możliwe aby utworzyć zakresy od 0 do N za pomocą operatora spread.

[...N] // zwraca teraz 0 ... N array

Http://jsfiddle.net/01e4xdv5/4/

Zdrówko.
 0
Author: Getriax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-30 11:53:11

Wiele z tych rozwiązań opiera się na tworzeniu instancji rzeczywistych obiektów tablicy, które mogą wykonać zadanie w wielu przypadkach, ale nie mogą obsługiwać takich przypadków jak range(Infinity). Możesz użyć prostego generatora, aby uniknąć tych problemów i obsługiwać nieskończone sekwencje:

function* range( start, end, step = 1 ){
  if( end === undefined ) [end, start] = [start, 0];
  for( let n = start; n < end; n += step ) yield n;
}

Przykłady:

Array.from(range(10));     // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

i = range(10, Infinity);
i.next(); // { value: 10, done: false }
i.next(); // { value: 11, done: false }
i.next(); // { value: 12, done: false }
i.next(); // { value: 13, done: false }
i.next(); // { value: 14, done: false }
 0
Author: Iron Savior,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-27 20:42:59

Dla liczb od 0 do 5

[...Array(5).keys()];
=> [0, 1, 2, 3, 4]
 0
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-03 09:11:17