How to create an array containing 1…N

后端 未结 30 1489
旧时难觅i
旧时难觅i 2020-11-22 01:04

I\'m looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runt

30条回答
  •  你的背包
    2020-11-22 01:48

    function range(start, end) {
        var foo = [];
        for (var i = start; i <= end; i++) {
            foo.push(i);
        }
        return foo;
    }
    

    Then called by

    var foo = range(1, 5);
    

    There is no built-in way to do this in Javascript, but it's a perfectly valid utility function to create if you need to do it more than once.

    Edit: In my opinion, the following is a better range function. Maybe just because I'm biased by LINQ, but I think it's more useful in more cases. Your mileage may vary.

    function range(start, count) {
        if(arguments.length == 1) {
            count = start;
            start = 0;
        }
    
        var foo = [];
        for (var i = 0; i < count; i++) {
            foo.push(start + i);
        }
        return foo;
    }
    

提交回复
热议问题