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

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

    Simple range function:

    function range(start, stop, step) {
        var a = [start], b = start;
        while (b < stop) {
            a.push(b += step || 1);
        }
        return a;
    }
    

    To incorporate the BitInt data type some check can be included, ensuring that all variables are same typeof start:

    function range(start, stop, step) {
        var a = [start], b = start;
        if (typeof start == 'bigint') {
            stop = BigInt(stop)
            step = step? BigInt(step): 1n;
        } else
            step = step || 1;
        while (b < stop) {
            a.push(b += step);
        }
        return a;
    }
    

    To remove values higher than defined by stop e.g. range(0,5,2) will include 6, which shouldn't be.

    function range(start, stop, step) {
        var a = [start], b = start;
        while (b < stop) {
            a.push(b += step || 1);
        }
        return (b > stop) ? a.slice(0,-1) : a;
    }
    

提交回复
热议问题