javascript 使用制表符或空格格式化文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17224130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting text with tabs or spaces
提问by hlcs
I have object like this:
我有这样的对象:
{
Name: "John"
Location: "Unknown"
Type: "Unknown"
Status: "Unknown"
Phone_number: "Unknown"
}
Need to format it like this (with tabs or spaces):
需要像这样格式化(使用制表符或空格):
Name: John // three tabs
Location: Unknown // two tabs
Type: Unknown // three tabs
Status: Unknown // three tabs
Phone_number: Unknown // one tab
Java and Perl has this functionality in printf, but how to do this in javascript?
Java 和 Perl在 printf 中有这个功能,但如何在 javascript 中做到这一点?
回答by hlcs
Ok. Found 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;
};
This not works with tabs, but works with spaces exactly how I describe in question.
这不适用于制表符,但适用于我所描述的空格。
For my example code will be:
对于我的示例代码将是:
$.each(myObj, function(myKey, myVal) {
myOut += myKey.padding(20) + " = " + myVal + "\r\n";
});
Output will be:
输出将是:
Name = John
Location = Unknown
Type = Unknown
Status = Unknown
Phone_number = Unknown
回答by Raul Martins
EDITYou can add more tabs by using '\t'. Each '\t' means one tab, so in the console.log you can use more console.log(prop + ":\t\t\t" + obj[prop]);
编辑您可以使用“\t”添加更多选项卡。每个 '\t' 表示一个选项卡,因此在 console.log 中您可以使用更多的 console.log(prop + ": \t\t\t" + obj[prop]);
Pass your object to this function (this works for any object):
将您的对象传递给此函数(这适用于任何对象):
function printObject(obj)
for(var prop in obj){
if (obj.hasOwnProperty(prop)) {
console.log(prop + ":\t" + obj[prop]);
}
}
You can also get a pretty similar output (but with quotes) by using
您还可以通过使用获得非常相似的输出(但带引号)
JSON.stringify(obj, null, 2);
This will basically print your objects in jason format and will use the last argument (the 2) as the number of separator spaces.
这将基本上以 jason 格式打印您的对象,并将使用最后一个参数(2)作为分隔符空格的数量。