如何使用 underscore.js 和前导 0 生成一系列数字?

How generate a range of numbers using underscore.js with leading 0s?

我一直在尝试为用户要 select 小时、分钟的下拉菜单生成值。

为了获得分钟的可能值,我使用了这个:

_.range(1, 61)

这会生成类似

的数组
[1, 2, 3 ... 60] 

但我要求它的格式为

[01, 02, 03 ... 60] 

是否有使用下划线的简洁方法?

将其放在 javascript 文件的顶部...

Number.prototype.pad = function (count) {
   var num = this.valueOf();
   var ret = "";
   for (var i = 0; i < count - num.toString().length; i++) {
       ret += "0";
   }
   ret += num;
   return ret;
}

然后 return ...

_.range(1, 61).map(function (num) { return num.pad(2) })

这将给出长度为 2 的前导 0 的字符串数组

只有字符串数组才有可能:

var 
  range = _.range(1, 61),
  i,
  arr = [];

for (i in range) {

  if (range[i] <= 9) {

    arr.push('0' + range[i]);
  }
  else {

    arr.push('' + range[i]);                      
  }
}

结果:

console.log(arr); // ["01", "02" ... "61"]

Object-Oriented JavaScript - Second Edition When a number starts with a 0, it's considered an octal number. For example, the octal 0377 is the decimal 255:

var n3 = 0377;

typeof n3; // "number"

n3; // 255

The last line in the preceding example prints the decimal representation of the octal value.

parseInt('0377', 8); // 255

ECMAScript 5 removes the octal literal values and avoids the confusion with parseInt() and unspecified radix.

在 FF 中,很快在其他浏览器中,使用 padStart:

_.range(1, 61) . map(num => String(num).padStart(2, '0'))

另一种方法是

_.range(1, 61) . map(num => ('0' + num).slice(-2));

这会在所有数字的开头添加一个零,但随后只取结果的最后两个字符。

函数式方法是编写一个接受长度的高阶函数和returns一个将输入填充到该长度的函数:

function make_padder(len) {
  return str => ('0000000000000' + str).slice(-len);
}

现在你可以写了

_.range(1,61) . map(make_padder(2))