在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
我在写一个数字基础转换器时,想到了一个荒谬的单行程序。
//这是被诅咒的 函数p (i, w、z) {z z = | | 0; w = w | | 8; i + = "; var o w = i.length %;还啊?[…数组(言).fill (z),……我]. join():我;} console.log (p (8675309));//默认:pad w/ 0到8位 console.log (p(525600年,10));//输入10个数字 console.log(p(69420, 10, 'X'));// Pad w/ X到10位 console.log (p (8675309, 4));//输入4位数字 console.log (p (12345678));//没必要就别拍
或者,以一种不那么容易暴露我把灵魂出卖给黑Perl的形式:
function pad(input, width, zero) {
zero = zero || 0; width = width || 8; // Defaults
input += ''; // Convert input to string first
var overflow = input.length % width // Do we overflow?
if (overflow) { // Yep! Let's pad it...
var needed = width - overflow; // ...to the next boundary...
var zeroes = Array(needed); // ...with an array...
zeroes = zeroes.fill(zero); // ...full of our zero character...
var output = [...zeroes,...input]; // ...and concat those zeroes to input...
output = output.join(''); // ...and finally stringify.
} else {
var output = input; // We don't overflow; no action needed :)
}
return output; // Done!
}
这个答案与其他答案不同的一点是,它取数字长度对目标宽度的模,而不是简单的大于检查。如果你想确保结果长度是目标宽度的倍数(例如,你需要输出5或10个字符长),这是很方便的。
我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!
其他回答
不要白费力气;使用下划线字符串:
js小提琴
var numToPad = '5';
alert(_.str.pad(numToPad, 6, '0')); // Yields: '000005'
我发现这个问题很有趣,我贡献了自己的一份力量
function zeroLeftComplete(value, totalCharters = 3) { const valueString = value.toString() || '0' const zeroLength = valueString.length - totalCharters if (Math.sign(parseInt(zeroLength)) === -1) { const zeroMissing = Array.from({ length: Math.abs(zeroLength) }, () => '0').join('') return `${zeroMissing}${valueString}` } else return valueString }; console.log(zeroLeftComplete(0)); console.log(zeroLeftComplete(1)); console.log(zeroLeftComplete(50)); console.log(zeroLeftComplete(50561,3));
如果性能真的很关键(遍历数百万条记录),则可以预先生成填充字符串数组,从而避免每次调用都这样做。
时间复杂度:O(1)。 空间复杂度:O(1)。
const zeroPads = Array.from({ length: 10 }, (_, v) => '0'.repeat(v)) 函数 zeroPad(num, len) { const numStr = String(num) return (zeroPads[len - numStr.length] + numStr) }
以下提供了一个快速的解决方案:
函数numberPadLeft(num, max, padder = "0"){ 返回"" == (num += "") ?“”: (dif = Max - num.length, dif > 0 ? 微调电容器。重复(dif < 0 ?0: dif) + num: num) }
我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作
(也适用于负数和小数)
代码:
function fillZeroes(n = 0, m = 1) {
const p = Math.max(1, m);
return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}
输出:
console.log(fillZeroes(6, 2)) // >> '06'
console.log(fillZeroes(1.35, 2)) // >> '01.35'
console.log(fillZeroes(-16, 3)) // >> '-016'
console.log(fillZeroes(-1.456, 3)) // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3)) // >> 'Agent 007'