我需要一个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) );


当前回答

ECMAScript 2017在String原型中增加了一个padStart方法。这个方法将用空格填充字符串到给定的长度。此方法还接受一个可选字符串,该字符串将用于代替空格作为填充。

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

还添加了以相同方式工作的padEnd方法。

关于浏览器兼容性(和一个有用的填充),请参见此链接。

其他回答

使用ECMAScript 6方法String#repeat和Arrow函数,一个pad函数就像这样简单:

var leftPad = (s, c, n) => c.repeat(n - s.length) + s;
leftPad("foo", "0", 5); //returns "00foo"

斯菲德尔

编辑: 评论中的建议:

const leftPad = (s, c, n) => n - s.length > 0 ? c.repeat(n - s.length) + s : s;

这样,当s.lengthis大于n时,它就不会抛出错误

edit2: 评论中的建议:

const leftPad = (s, c, n) =>{ s = s.toString(); c = c.toString(); return s.length > n ? s : c.repeat(n - s.length) + s; }

通过这种方式,可以将该函数用于字符串和非字符串。

一种更快的方法

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站点已不再在线。不幸的是,这意味着我们无法得到那些测试结果。虽然悲伤,但事实如此。

如果你只是想要一个非常简单的单行程序来填充,只需创建一个所需填充字符的字符串,以及所需的最大填充长度,然后将其子字符串转换为你想要填充的长度。

示例:用空格填充e中的字符串存储到25个字符长。

var e = "hello"; e = e + "                         ".substring(e.length)

结果:“hello”

如果你想用一个数字作为输入做同样的事情,只需在它之前调用. tostring()。

如果你想要一些紧凑的东西,只需一行:

String.prototype.pad = function(len, chr){ 返回((((新数组(len)) .fill(杆)). join (" ") +) .substring (this.length)); }

这里有一个你可以使用的内置方法-

str1.padStart(2, '0')