Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

后端 未结 30 3233
广开言路
广开言路 2020-11-22 00:51

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range(\"A\", \"C\"); // Array(\"A\", \"B\", \"C\")

That is, there is a function that l

30条回答
  •  耶瑟儿~
    2020-11-22 01:41

    range(start,end,step): With ES6 Iterators

    You only ask for an upper and lower bounds. Here we create one with a step too.

    You can easily create range() generator function which can function as an iterator. This means you don't have to pre-generate the entire array.

    function * range ( start, end, step = 1 ) {
      let state = start;
      while ( state < end ) {
        yield state;
        state += step;
      }
      return;
    };
    

    Now you may want to create something that pre-generates the array from the iterator and returns a list. This is useful for functions that accept an array. For this we can use Array.from()

    const generate_array = (start,end,step) =>
      Array.from( range(start,end,step) );
    

    Now you can generate a static array easily,

    const array1 = generate_array(1,10,2);
    const array1 = generate_array(1,7);
    

    But when something desires an iterator (or gives you the option to use an iterator) you can easily create one too.

    for ( const i of range(1, Number.MAX_SAFE_INTEGER, 7) ) {
      console.log(i)
    }
    

    Special Notes

    • If you use Ramda, they have their own R.range as does Lodash

提交回复
热议问题