A function to create flexibly-numbered lists of integers, handy for each and maploops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers fromstart to stop, incremented (or decremented) by step, exclusive.
建立一个包含指定范围单元的数组
1 _.range(10); 2 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 _.range(1, 11); 4 => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5 _.range(0, 30, 5); 6 => [0, 5, 10, 15, 20, 25] 7 _.range(0, -10, -1); 8 => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] 9 _.range(0); 10 => []
源码:
1 _.range = function(start, stop, step) { 2 if (arguments.length <= 1) { 3 stop = start || 0; 4 start = 0; 5 } 6 step = arguments[2] || 1; 7 8 var len = Math.max(Math.ceil((stop - start) / step), 0); 9 var idx = 0; 10 var range = new Array(len); 11 12 while(idx < len) { 13 range[idx++] = start; 14 start += step; 15 } 16 17 return range; 18 };