使用console.table()调试javascript

作者:袖梨 2022-11-14

或许你已经习惯了console.log()来调试js,非常好用,但是今天微博看到console.table()调试javascript,和console.log()类似,主要区别在于:

主要用来输出对象和数组;
更加直接的可视化,以表格形式展现;
可以单独输出某个或某几个属性

代码如下 复制代码









由于本人英文不好不懂译了,直接上英文后面有地址大家可进入参考。

Imagine you have created this list of programming languages and their file extensions:

代码如下 复制代码

var languages = [
{ name: "JavaScript", fileExtension: ".js" },
{ name: "TypeScript", fileExtension: ".ts" },
{ name: "CoffeeScript", fileExtension: ".coffee" }
];

console.log(languages);

The console.log() call will give you the following representation of your data:

That tree view is helpful for debugging purposes, but I find it a little cumbersome to have to open every collapsed object manually. I'm saying we can do a little better with console.table().

Logging Array Data with console.table()
Instead of calling console.log(), we'll use console.table() now:

console.table(languages);
Make sure the console is opened before refreshing the page, otherwise you won't see any output. If you did everything correct, you'll be rewarded with this nice, little table view:

Pretty neat, isn't it?

Of course, tables work best for tabular data. If all the objects have a totally different structure, you'll end up with most of the cells containing undefined values. Still, the property values are neatly arranged and give you a good overview.

Logging Object Data with console.table()
Another nice thing about console.table() is that it also works with objects:

代码如下 复制代码

var languages = {
csharp: { name: "C#", paradigm: "object-oriented" },
fsharp: { name: "F#", paradigm: "functional" }
};

console.table(languages);


'nuff said.

Filtering the Displayed Object Properties
If you want to restrict the columns to certain properties, you can pass an array of their keys as a second parameter to the console.table() call:

代码如下 复制代码

// Multiple property keys
console.table(languages, ["name", "paradigm"]);
For a single property, a simple string is sufficient:

// A single property key
console.table(languages, "name");

如果你看不懂上在,可进入看英文:http://www.mariusschulz.com/2013/11/13/advanced-javascript-debugging-with-consoletable

相关文章

精彩推荐