[英]Automatically console.log the name and value of all variables in a script
[英]Console.log is there a way to name sent variables?
將項目發送到 console.log 時有沒有辦法給它們命名? 類似於視覺工作室中的“觀看”
例如我們有一個var counter=1;
以便在控制台日志中顯示為:
counter 1
counter 2
等等 ....
不直接,但您可以在輸出它們時命名它們。
console.log
(和.error
、 .info
和.warn
)讓你可以同時傳遞任意數量的值,所以做這樣的事情非常容易:
console.log('counter', counter);
輸出如下:
counter 1
let counter = 0; for (let i = 0; i < 5; i++) { counter++; console.log('counter', counter); }
您還可以在對象內通過控制台將它們注銷,以便您能夠訪問其名稱和值。
var counter = 5;
輸入:
console.log({counter});
輸出:
{counter: 5}
您可以使用標簽字符串后跟變量名稱和中間的“+”運算符,如下所示:
console.log("Counter : " + counter);
有一種解決方法
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.