How to create an array containing 1…N

后端 未结 30 2154
旧时难觅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 02:03

    If you are using lodash, you can use _.range:

    _.range([start=0], end, [step=1])

    Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. A step of -1 is used if a negative start is specified without an end or step. If end is not specified, it's set to start with start then set to 0.

    Examples:

    _.range(4);
    // ➜ [0, 1, 2, 3]
    
    _.range(-4);
    // ➜ [0, -1, -2, -3]
    
    _.range(1, 5);
    // ➜ [1, 2, 3, 4]
    
    _.range(0, 20, 5);
    // ➜ [0, 5, 10, 15]
    
    _.range(0, -4, -1);
    // ➜ [0, -1, -2, -3]
    
    _.range(1, 4, 0);
    // ➜ [1, 1, 1]
    
    _.range(0);
    // ➜ []
    

提交回复
热议问题