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

后端 未结 30 2794
广开言路
广开言路 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:38

    OK, in JavaScript we don't have a range() function like PHP, so we need to create the function which is quite easy thing, I write couple of one-line functions for you and separate them for Numbers and Alphabets as below:

    for Numbers:

    function numberRange (start, end) {
      return new Array(end - start).fill().map((d, i) => i + start);
    }
    

    and call it like:

    numberRange(5, 10); //[5, 6, 7, 8, 9]
    

    for Alphabets:

    function alphabetRange (start, end) {
      return new Array(end.charCodeAt(0) - start.charCodeAt(0)).fill().map((d, i) => String.fromCharCode(i + start.charCodeAt(0)));
    }
    

    and call it like:

    alphabetRange('c', 'h'); //["c", "d", "e", "f", "g"]
    

提交回复
热议问题