How to create an array containing 1…N

后端 未结 30 1487
旧时难觅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:47

    Use the very popular Underscore _.range method

    // _.range([start], stop, [step])
    
    _.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    _.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    _.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
    _.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    _.range(0); // => []
    

提交回复
热议问题