我经常发现编写 JavaScript 时最重复的任务之一是需要不断检查变量的值,尤其是当脚本变得越来越复杂时。
有没有办法通过调用函数自动将变量值记录到控制台?
例如
var foo = 1,
bar = true,
yin = ['item 1', 'item 2'],
yang = 'a string',
tan = $(this);
function() {
yang = 'another string';
}
foo += 1;
yin.push('item 3');
function logMyVariables();
会记录:
foo: 2
bar: true
yin: item1, item2, item 3
yang: another string
tan: [object Object]
最佳答案
您可以调用debugger;
。这将暂停您的脚本,并为您提供此时许多事物的快照,包括所有变量、本地变量和全局变量。
尝试在打开的开发工具下运行下面的代码片段,您将看到结果。这至少适用于 Chrome 和 Firefox。
function init() {
var foo = 1,
bar = true,
yin = ['item 1', 'item 2'],
yang = 'a string',
tan = this;
(function(){
yang = 'another string';
}());
foo += 1;
yin.push('item 3');
debugger;
}
init();
关于javascript - 自动 console.log 脚本中所有变量的名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369141/