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

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

    As far as generating a numeric array for a given range, I use this:

    function range(start, stop)
    {
        var array = [];
    
        var length = stop - start; 
    
        for (var i = 0; i <= length; i++) { 
            array[i] = start;
            start++;
        }
    
        return array;
    }
    
    console.log(range(1, 7));  // [1,2,3,4,5,6,7]
    console.log(range(5, 10)); // [5,6,7,8,9,10]
    console.log(range(-2, 3)); // [-2,-1,0,1,2,3]
    

    Obviously, it won't work for alphabetical arrays.

提交回复
热议问题