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


当前回答

有点晚了,但我还是想分享一下。我发现向Object添加一个原型扩展很有用。这样我就可以填充数字和字符串,向左或向右。我有一个模块与类似的实用程序,我包括在我的脚本。

// include the module in your script, there is no need to export
var jsAddOns = require('<path to module>/jsAddOns');

~~~~~~~~~~~~ jsAddOns.js ~~~~~~~~~~~~

/* 
 * method prototype for any Object to pad it's toString()
 * representation with additional characters to the specified length
 *
 * @param padToLength required int
 *     entire length of padded string (original + padding)
 * @param padChar optional char
 *     character to use for padding, default is white space
 * @param padLeft optional boolean
 *     if true padding added to left
 *     if omitted or false, padding added to right
 *
 * @return padded string or
 *     original string if length is >= padToLength
 */
Object.prototype.pad = function(padToLength, padChar, padLeft) {    

    // get the string value
    s = this.toString()

    // default padToLength to 0
    // if omitted, original string is returned
    padToLength = padToLength || 0;

    // default padChar to empty space
    padChar = padChar || ' ';


    // ignore padding if string too long
    if (s.length >= padToLength) {
        return s;
    }

    // create the pad of appropriate length
    var pad = Array(padToLength - s.length).join(padChar);

    // add pad to right or left side
    if (padLeft) {
        return pad  + s;        
    } else {
        return s + pad;
    }
};

其他回答

I think its better to avoid recursion because its costly. function padLeft(str,size,padwith) { if(size <= str.length) { // not padding is required. return str; } else { // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below) // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000' // 3- now append '000' with orginal string (str = 55), will produce 00055 // why +1 in size of array? // it is a trick, that we are joining an array of empty element with '0' (in our case) // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined). // <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array return Array(size-str.length+1).join(padwith||'0')+str } } alert(padLeft("59",5) + "\n" + padLeft("659",5) + "\n" + padLeft("5919",5) + "\n" + padLeft("59879",5) + "\n" + padLeft("5437899",5));

使用默认值的填充

我注意到我主要需要padLeft进行时间转换/数字填充。

所以我写了这个函数:

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + a).slice(-b)
}

这个简单的函数支持数字或字符串作为输入。

默认的pad是两个字符。

默认字符为0。

所以我可以简单地写:

padL(1);
// 01

如果我添加第二个参数(pad width):

padL(1, 3);
// 001

第三个参数(填充字符)

padL('zzz', 10, 'x');
// xxxxxxxzzz

@BananaAcid:如果你传递一个未定义的值或长度为0的字符串,你会得到0undefined,所以:

作为建议

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array((b || 1) + 1).join(c || 0) + (a || '')).slice(-(b || 2))
}

但这也可以用更短的方式实现。

function padL(a, b, c) { // string/number, length=2, char=0
  return (new Array(b || 2).join(c || 0) + (a || c || 0)).slice(-b)
}

它还适用于:

padL(0)
padL(NaN)
padL('')
padL(undefined)
padL(false)

如果你想用两种方式填充:

function pad(a, b, c, d) { // string/number, length=2, char=0, 0/false=Left-1/true=Right
  return a = (a || c || 0), c = new Array(b || 2).join(c || 0), d ? (a + c).slice(0, b) : (c + a).slice(-b)
}

不用slice就可以写得更简洁。

function pad(a, b, c, d) {
  return a = (a || c || 0) + '', b = new Array((++b || 3) - a.length).join(c || 0), d ? a+b : b+a
}
/*

Usage:

pad(
 input // (int or string) or undefined, NaN, false, empty string
       // default:0 or PadCharacter
 // Optional
 ,PadLength // (int) default:2
 ,PadCharacter // (string or int) default:'0'
 ,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight
)

*/

现在如果你试着用2填充'averylongword'…那不是我的问题。


我说过我会给你小费。

大多数情况下,如果你填充,你会做N次相同的值。

在循环中使用任何类型的函数都会降低循环的速度!!

所以如果你只是想在一个长列表中填充一些数字,不要使用函数来做这个简单的事情。

可以这样说:

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7],
    paddedArray = [],
    len = arrayOfNumbers.length;
while(len--) {
  paddedArray[len] = ('0000' + arrayOfNumbers[len]).slice(-4);
}

如果你不知道如何根据数组内的数字来确定最大填充大小。

var arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 49095],
    paddedArray = [],
    len = arrayOfNumbers.length;

// Search the highest number
var arrayMax = Function.prototype.apply.bind(Math.max, null),
// Get that string length
padSize = (arrayMax(arrayOfNumbers) + '').length,
// Create a Padding string
padStr = new Array(padSize).join(0);
// And after you have all this static values cached start the loop.
while(len--) {
  paddedArray[len] = (padStr + arrayOfNumbers[len]).slice(-padSize); // substr(-padSize)
}
console.log(paddedArray);

/*
0: "00001"
1: "00002"
2: "00003"
3: "00004"
4: "00005"
5: "00006"
6: "00007"
7: "49095"
*/
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”

这是我的函数版本:

function str_pad(str, size, char, right) {
    var s = str + "";
    while (s.length < size) {
        if (right) {
            s = s + char;
        } else {
            s = char + s;
        }
    }
    return s;
}

现在是2014年,我建议使用JavaScript字符串填充函数。哈!

基本的:带空格的右垫

function pad (str, length) {
    var padding = (new Array(Math.max(length - str.length + 1, 0))).join(" ");
    return str + padding;
}

花式:选项垫

/**
 * @param {*}       str                         Input string, or any other type (will be converted to string)
 * @param {number}  length                      Desired length to pad the string to
 * @param {Object}  [opts]
 * @param {string}  [opts.padWith=" "]          Character to use for padding
 * @param {boolean} [opts.padLeft=false]        Whether to pad on the left
 * @param {boolean} [opts.collapseEmpty=false]  Whether to return an empty string if the input was empty
 * @returns {string}
 */
function pad(str, length, opts) {
    var padding = (new Array(Math.max(length - (str + "").length + 1, 0))).join(opts && opts.padWith || " "),
        collapse = opts && opts.collapseEmpty && !(str + "").length;
    return collapse ? "" : opts && opts.padLeft ? padding + str : str + padding;
}

使用(的):

pad("123", 5);
// Returns "123  "

pad(123, 5);
// Returns "123  " - non-string input

pad("123", 5, { padWith: "0", padLeft: true });
// Returns "00123"

pad("", 5);
// Returns "     "

pad("", 5, { collapseEmpty: true });
// Returns ""

pad("1234567", 5);
// Returns "1234567"