以前除錯 JavaScript 只能靠寫滿地的 alert,每按一次確定就中斷一次流程。Firebug 帶進瀏覽器後,console.log 讓我們能把訊息直接印在控制台,不打斷執行、還能保留型別資訊。
<script type="text/javascript">
// 在 Firefox 中除錯
console.log("hello");
function test(name) {
console.log(name);
}
test("hello world");
</script>
console 不只 log,還分成 info、warn、error、debug 等等級,各自有不同的視覺標記,warn 與 error 更能直接在控制台被上色凸顯,方便快速掃視問題所在。
function showLog(message) {
console.log(message);
console.info(message);
console.warn(message);
console.error(message);
console.debug(message);
}
function test(name) {
showLog(name);
}
test("hello");
下面是一個累加 0 到 9 的小頁面,把結果寫進 div,用來示範如何搭配控制台與中斷點觀察流程:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>除錯示例</title>
<script type="text/javascript">
function method() {
var result = 0;
for (var i = 0; i < 10; i++) {
result += i;
}
document.getElementById("id1").innerHTML = result;
}
</script>
</head>
<body>
<input type="button" value="click" onclick="method()" />
<div id="id1"></div>
</body>
</html>
除了印訊息,Firebug 還能在 script 面板設中斷點、單步執行、在表達式面板任意求值;console 也支援 console.dir(obj) 展開物件結構、console.table() 以表格呈現陣列。今天的 Chrome DevTools 大致沿用了這套介面與 API,當年學的習慣到現在仍然通用。