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


当前回答

String.prototype.padStart()和String.prototype.padEnd()目前是TC39候选提案:参见github.com/tc39/proposal-string-pad-start-end(仅在2016年4月在Firefox中可用;有填充材料可用)。

其他回答

以下是我的看法:

我不太确定它的性能,但我发现它比我在这里看到的其他选项更具可读性……

var replicate = function(len, char) {
  return Array(len + 1).join(char || ' ');
};

var padr = function(text, len, char) {
  if (text.length >= len)
    return text;
  return text + replicate(len-text.length, char);
};

在ES8中,有两个填充选项。

您可以在文档中查看它们。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

这是一个递归的方法。

function pad(width, string, padding) { 
  return (width <= string.length) ? string : pad(width, padding + string, padding)
}

一个例子……

pad(5, 'hi', '0')
=> "000hi"

填充字符串已在新的javascript版本中实现。

str.padStart(目标,pad弦)

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

如果你想要自己的函数,检查这个例子:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house

我将上述解决方案的组合添加到我自己的,总是不断发展的版本:)

//in preperation for ES6
String.prototype.lpad || (String.prototype.lpad = function( length, charOptional )
{
    if (length <= this.length) return this;
    return ( new Array((length||0)+1).join(String(charOptional)||' ') + (this||'') ).slice( -(length||0) );
});


'abc'.lpad(5,'.') == '..abc'
String(5679).lpad(10,0) == '0000005679'
String().lpad(4,'-') == '----' // repeat string