我有这样的对象:

{
 Name: "John"
 Location: "Unknown"
 Type: "Unknown"
 Status: "Unknown"
 Phone_number: "Unknown"
}

需要这样格式化(带有制表符或空格):
Name:           John // three tabs
Location:       Unknown // two tabs
Type:           Unknown // three tabs
Status:         Unknown // three tabs
Phone_number:   Unknown // one tab

Java和Perl都有这个functionality in printf,但是如何在javascript中做到这一点?

最佳答案

好。找到here:

/**
 * object.padding(number, string)
 * Transform the string object to string of the actual width filling by the padding character (by default ' ')
 * Negative value of width means left padding, and positive value means right one
 *
 * @param       number  Width of string
 * @param       string  Padding chacracter (by default, ' ')
 * @return      string
 * @access      public
 */
String.prototype.padding = function(n, c)
{
        var val = this.valueOf();
        if ( Math.abs(n) <= val.length ) {
                return val;
        }
        var m = Math.max((Math.abs(n) - this.length) || 0, 0);
        var pad = Array(m + 1).join(String(c || ' ').charAt(0));
//      var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
        return (n < 0) ? pad + val : val + pad;
//      return (n < 0) ? val + pad : pad + val;
};

这不适用于制表符,但完全适用于我所描述的空格。

对于我的示例代码将是:
$.each(myObj, function(myKey, myVal) {

   myOut += myKey.padding(20) + " = " + myVal + "\r\n";

});

输出将是:
Name                 = John
Location             = Unknown
Type                 = Unknown
Status               = Unknown
Phone_number         = Unknown

09-27 21:49
查看更多