如何在Google Chrome JavaScript控制台中打印调试消息
在控制台中打印消息非常简单,我们只需要知道如何在Chrome上激活控制台以进行查看。控制台始终处于活动状态,我们只是使其对前端可见而已。控制台是一个对象,提供了对浏览器调试控制台的访问。控制台对象有很多方法可以帮助我们打印自定义的调试信息。以下是一些常用方法:
- assert(): 类似于 ‘if’,如果条件为假,则在控制台上打印消息。
- clear(): 清空控制台。
- count(): 调用一次就计数一次。
- error(): 如果有错误,则打印错误消息。
- group(): 在控制台中创建新的内联组。
- groupCollapsed(): 创建新的内联折叠组。
- groupEnd(): 退出内联组。
- info(): 类似于log,用于重要信息。
- log(): 将消息输出到控制台。
- table(): 将表格数据显示为表格。
- time(): 跟踪特定任务所需的时间。
- timeEnd(): 停止跟踪。
- trace(): 输出堆栈跟踪。
- warn(): 输出警告消息。
运行脚本后按下F12,打开开发者工具,切换到顶部菜单中的控制台选项卡。
示例 1:
<!DOCTYPE html>
<html>
<body>
<h2>Debugging in Console</h2>
<p>On Clicking the below button,
myFunction() invokes and prints in the console.</p>
<input type="button"
onclick="myFunction()"
value="Tony send signal to Quill(console)">
<!--button-->
<script>
function myFunction() {
//prints in console
console.log("log:Tony sent a message");
//prints in console
console.info("info:Quill received.");
}
</script>
</body>
</html>
输出:
之前:
点击按钮之后:
示例2: 请查看控制台中的console.table()以更好地理解方法。
<!DOCTYPE html>
<html>
<body>
<h2>Debugging in Console</h2>
<p>On Clicking the below button,
myFunction() invokes and prints in the console.</p>
<input type="button"
onclick="myFunction()"
value="who are the guardians?">
<script>
function myFunction() {
console.table(["Quill", "Gamora", "Drax",
"Groot", "Rocket", "mantis"]);
}
</script>
</body>
</html>
输出
之前:
点击按钮后: