我很确定某个库/ NPM模块中存在这样的功能,唉,我试图找到一个失败了。
我正在寻找此代码段中range()
函数行的内容:
var a = range(4);
expect(a).toEqual([0, 1, 2, 3]);
答案 0 :(得分:4)
http://underscorejs.org/#range
_.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);
=> []
答案 1 :(得分:3)
您可以使用此oneliner创建一个(来源:Creating range in JavaScript - strange syntax)
function range(end) {
return Array.apply(null, {length: end}).map(Number.call, Number);
}
console.log(range(4));
// [ 0, 1, 2, 3 ]
答案 2 :(得分:0)
Underscore的范围实施:
function range(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(length);
while(idx < length) {
range[idx++] = start;
start += step;
}
return range;
};
用法:
// stop 10
range(10); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// start 5, stop 10
range(5, 10); //[5, 6, 7, 8, 9]
// start 1, stop 10, step 2
range(1, 10, 2); //[1, 3, 5, 7, 9]