我需要一个JavaScript函数,它可以取一个值,并将其填充到给定的长度(我需要空格,但任何事情都会做)。我发现了这个,但我不知道它在做什么,它似乎对我不起作用。
String.prototype.pad = function(l, s, t) {
return s || (s = " "),
(l -= this.length) > 0 ?
(s = new Array(Math.ceil(l / s.length) + 1).join(s))
.substr(0, t = !t ? l : t == 1 ?
0 :
Math.ceil(l / 2)) + this + s.substr(0, l - t) :
this;
};
var s = "Jonas";
document.write(
'<h2>S = '.bold(), s, "</h2>",
'S.pad(20, "[]", 0) = '.bold(), s.pad(20, "[]", 0), "<br />",
'S.pad(20, "[====]", 1) = '.bold(), s.pad(20, "[====]", 1), "<br />",
'S.pad(20, "~", 2) = '.bold(), s.pad(20, "~", 2)
);
一个朋友问我如何使用JavaScript函数向左填充。它变成了我们中的一些人在聊天中努力编码高尔夫球。结果是:
function l(p,t,v){
v+="";return v.length>=t?v:l(p,t,p+v);
}
它确保要填充的值是一个字符串,然后如果它不是所需的总长度,它将填充一次,然后递归。下面是它看起来更有逻辑的命名和结构
function padLeft(pad, totalLength, value){
value = value.toString();
if( value.length >= totalLength ){
return value;
}else{
return padLeft(pad, totalLength, pad + value);
}
}
我们所使用的示例是确保数字在左边用0填充,使最大长度为6。下面是一个例子:
函数l (p t v) {v + = " ";返回v.length > = t ? v: l (p t, p + v);}
Var vals = [6451,123,466750];
Var pad = l(0,6,vals[0]);// pad为0,最大长度为6
Var pads = vals.map(函数(i){返回l(0,6,i)});
document . write(垫。加入(“< br / > "));
一种更快的方法
If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.
function pad(pad, str, padLeft) {
if (typeof str === 'undefined')
return pad;
if (padLeft) {
return (pad + str).slice(-pad.length);
} else {
return (str + pad).substring(0, pad.length);
}
}
例如,要将一个数字零填充为10位,
pad('0000000000',123,true);
要用空格填充字符串,使整个字符串为255个字符,
var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);
性能测试
请在这里查看jsPerf测试。
这比ES6字符串快。重复2倍,正如这里修改后的JsPerf所示
请注意,jsPerf不再联机
请注意,我们最初用来对各种方法进行基准测试的jsPerf站点已不再在线。不幸的是,这意味着我们无法得到那些测试结果。虽然悲伤,但事实如此。