我有同样的问题并写了下面的代码。它不像console.table那样功能齐全,它只接受记录数组,而不接受列列表。输出也不是很好,但对我来说已经足够了。一个例子:
$ console_table([{who:"World",message:"Hello"}
,{who:"My wife",message:"Good Morning!"}])
|who |message |
|World |Hello |
|My wife|Good Morning!|
以及它背后的代码:
// Will be available in the latest Chrome, then I can delete this
function console_table(xs)
{
if (xs.length === 0)
console.log("No data");
else
{
var widths = [];
var cells = [];
for (var i = 0; i <= xs.length; i++)
cells.push([]);
for (var s in xs[0])
{
var len = s.length;
cells[0].push(s);
for (var i = 0; i < xs.length; i++)
{
var ss = "" + xs[i][s];
len = Math.max(len, ss.length);
cells[i+1].push(ss);
}
widths.push(len);
}
var s = "";
for (var x = 0; x < cells.length; x++)
{
for (var y = 0; y < widths.length; y++)
s += "|" + pad(widths[y], cells[x][y]);
s += "|\n";
}
console.log(s);
}
}
function pad(n,s)
{
var res = s;
for (var i = s.length; i < n; i++)
res += " ";
return res;
}