简体   繁体   English

如何在console.log()中为每个值打印标签

[英]How to print out a label for each value in console.log()

I'm having trouble figuring out how to customize console.log() so that it automatically prints out the label for each argument I pass into it. 我在弄清楚如何自定义console.log()时遇到麻烦,以便它为我传入的每个参数自动打印出标签。 For example, I often do something like this, so that it's clear what each log is printing out: 例如,我经常做这样的事情,以便清楚地打印出每个日志的内容:

console.log('firstName: ', firstName);

I would love to be able to simplify this to: 我希望能够简化为:

my.log(firstName);

Is there any way to pass the variable names of the caller args into console.log() ? 有什么方法可以将调用方args的变量名传递给console.log()吗? Or is there another way to do this? 还是有其他方法可以做到这一点? My wish is that I don't have to type out the variable name twice, just the once. 我的愿望是我不必两次键入变量名,只需键入一次。 And ideally print out multiple arguments each with its own label on its own line in the console. 理想情况下,在控制台中的自己的行上打印出多个参数,每个参数都带有自己的标签。 I'm aware that I can access the arguments list, but I don't know how to un-eval() each argument to get just its variable name, if that makes sense. 我知道我可以访问参数列表,但是我不知道如何取消每个参数的eval()来获取其变量名(如果可以的话)。 I'm hoping it's something super-easy I missed. 我希望这是我错过的超级简单的事情。

Doing it the way you want is impossible (the log function doesn't know what name you called things.) The way I work around this is to use the object shorthand {firstName} to create a temporary object. 按照您想要的方式进行操作是不可能的(日志函数不知道您叫的名字)。我的解决方法是使用对象速记{firstName}创建一个临时对象。

You can then either use .log or .table to display it: 然后,您可以使用.log.table来显示它:

 const firstName = 'bob'; console.log({firstName}); console.table({firstName}); // It also works for multiple variables: const lastName = 'smith'; console.log({firstName, lastName}); 

You could use console.table() to print things in a more readable form: 您可以使用console.table()以更易读的形式打印内容:

(Look in the real console to see it.) (查看真实控制台以查看它。)

 var obj = { firstName: "name", lastName: "smith" }; function log(obj) { console.table(obj); } log(obj); 

Try this : 尝试这个 :

 var my = { log : function(name) { console.log('firstName: ', name); } }; my.log("Rohit"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM