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


当前回答

Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end! Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

if (!String.prototype.lpad) { String.prototype.lpad =函数(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回垫。Substr (0, lens -this.length) + this; } } if (!String.prototype.rpad) { String.prototype.rpad = function(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回这个+ pad。substr (0, len-this.length); } }

其他回答

与简单的字符串连接相比,数组操作真的很慢。当然,是用例的基准测试。

function(string, length, pad_char, append) {
    string = string.toString();
    length = parseInt(length) || 1;
    pad_char = pad_char || ' ';

    while (string.length < length) {
        string = append ? string+pad_char : pad_char+string;
    }
    return string;
};

还有一种结合了几个解决方案的方法:

/**
 * pad string on left
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingLeft = function (b, c) {
    if (this.length > (b||2))
        return this + '';
  return (this || c || 0) + '', b = new Array((++b || 3) - this.length).join(c || 0), b + this
};

/**
 * pad string on right
 * @param {number} number of digits to pad, default is 2
 * @param {string} string to use for padding, default is '0' *
 * @returns {string} padded string
 */
String.prototype.paddingRight = function (b, c) {
  if (this.length > (b||2))
        return this + '';
  return (this||c||0) + '', b = new Array((++b || 3) - this.length).join(c || 0), this + b
};

Never insert data somewhere (especially not at beginning, like str = pad + str;), since the data will be reallocated everytime. Append always at end! Don't pad your string in the loop. Leave it alone and build your pad string first. In the end concatenate it with your main string. Don't assign padding string each time (like str += pad;). It is much faster to append the padding string to itself and extract first x-chars (the parser can do this efficiently if you extract from first char). This is exponential growth, which means that it wastes some memory temporarily (you should not do this with extremely huge texts).

if (!String.prototype.lpad) { String.prototype.lpad =函数(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回垫。Substr (0, lens -this.length) + this; } } if (!String.prototype.rpad) { String.prototype.rpad = function(pad, len) { 而(pad。长度< len) { Pad += Pad; } 返回这个+ pad。substr (0, len-this.length); } }

函数 var _padLeft = function(paddingString, width, replacementChar) { paddingString返回。长度>=宽度?paddingString: _padLeft(replacementChar + paddingString, width, replacementChar || ' '); }; 字符串的原型 String.prototype.padLeft = function(width, replacementChar) { 返回。长度>=宽度?this. tostring ():(replacementChar + this)。padLeft(width, replacementChar || ' '); }; 片 ('00000' + paddingString).slice(-5)

String.prototype.padLeft = function(pad) {
        var s = Array.apply(null, Array(pad)).map(function() { return "0"; }).join('') + this;
        return s.slice(-1 * Math.max(this.length, pad));
    };

用法:

“123”.padLeft(2) 返回:“123” “12”.padLeft(2) 返回:“12” “1”.padLeft(2) 返回:“01”