Console.log is there a way to name sent variables?

為{幸葍}努か 提交于 2019-12-02 10:59:32

问题


When sending items to console.log is there a way to name them? Similar to "watch" in visual studio

for example we have a var counter=1; so that in the console log it appears as:

counter 1
counter 2

and so on ....


回答1:


Not directly, but you can just name them when you output them.

console.log (and .error, .info, and .warn) let you pass any number of values at the same time, so it's super easy to just do something like this:

console.log('counter', counter);

which would output like:

counter 1

let counter = 0;

for (let i = 0; i < 5; i++) {
  counter++;
  console.log('counter', counter);
}



回答2:


You can use the label string followed by variable name and a "+" operator in between, as follows:

console.log("Counter : " + counter);



回答3:


There is one workaround

function p(variableInObject) {
    let name = Object.keys(variableInObject)[0]
    let value = variableInObject[name] 
    console.log(name, value)
}
let g = 5
p({g}) // g 5
// it even works with loops
for (let i = 0; i < 3; i++) {
  p({i})  // i 0, then i 1, then i 2
}


来源:https://stackoverflow.com/questions/44802044/console-log-is-there-a-way-to-name-sent-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!