在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:
function zerofill(number, width) {
var num = '';
while (width-- > 0) {
num += '0';
}
return num.slice(0, - (number + '').length) + number + '';
}
其他回答
这一种不太本土,但可能是最快的…
zeroPad = function (num, count) {
var pad = (num + '').length - count;
while(--pad > -1) {
num = '0' + num;
}
return num;
};
仅供参考,更清晰,更可读的语法恕我直言
"use strict";
String.prototype.pad = function( len, c, left ) {
var s = '',
c = ( c || ' ' ),
len = Math.max( len, 0 ) - this.length,
left = ( left || false );
while( s.length < len ) { s += c };
return ( left ? ( s + this ) : ( this + s ) );
}
Number.prototype.pad = function( len, c, left ) {
return String( this ).pad( len, c, left );
}
Number.prototype.lZpad = function( len ) {
return this.pad( len, '0', true );
}
这也导致结果的视觉和可读性问题比其他一些解决方案更少,这些解决方案强制'0'作为字符;回答我的问题,我该怎么做,如果我想垫其他字符,或在其他方向(右填充),同时保持容易打字,并清楚地阅读。我敢肯定,这也是DRY的最佳示例,实际的前导零填充函数体的代码最少(因为其他相关函数在很大程度上与这个问题无关)。
该代码可通过github用户的gist进行评论(代码的原始来源) https://gist.github.com/Lewiscowles1986/86ed44f428a376eaa67f
在控制台和脚本测试中注意,数值文字似乎需要括号或变量才能调用方法,因此2.pad(…)将导致错误,而(2).pad(0,'#')不会。这似乎对所有数字都是一样的
post,如果这是你正在寻找的,将剩余的时间以毫秒为单位转换为字符串,如00:04:21
function showTimeRemaining(remain){
minute = 60 * 1000;
hour = 60 * minute;
//
hrs = Math.floor(remain / hour);
remain -= hrs * hour;
mins = Math.floor(remain / minute);
remain -= mins * minute;
secs = Math.floor(remain / 1000);
timeRemaining = hrs.toString().padStart(2, '0') + ":" + mins.toString().padStart(2, '0') + ":" + secs.toString().padStart(2, '0');
return timeRemaining;
}
我觉得我的方法有点不同。我需要填充一个数字的原因是在<pre>元素(屏幕日志的一部分)中显示它,所以它最终将是一个字符串。我没有做任何数学运算,而是写了一个简单的函数来覆盖一个掩码字符串上的字符串值:
function overlayr(m, s) {
return m.length > s.length ? m.substr(0, m.length - s.length) + s : s;
}
这样做的好处是,我可以将它用于各种字符串对齐任务。要调用它,只需传入掩码和数字作为字符串:
> overlayr('00000', (5).toString())
< "00005"
作为一个额外的好处,它可以正确地处理溢出:
> overlayr('00000', (555555).toString())
< "555555"
当然它不局限于0填充:
> overlayr('*****', (55).toString())
< "***55"
如果填充数事先知道不超过某个值,还有另一种不循环的方法:
var fillZeroes = "00000000000000000000"; // max number of zero fill ever asked for in global
function zeroFill(number, width) {
// make sure it's a string
var input = number + "";
var prefix = "";
if (input.charAt(0) === '-') {
prefix = "-";
input = input.slice(1);
--width;
}
var fillAmt = Math.max(width - input.length, 0);
return prefix + fillZeroes.slice(0, fillAmt) + input;
}
测试用例在这里:http://jsfiddle.net/jfriend00/N87mZ/