說白了,console.log 就是一個能把 JS 陣列與物件印出來的函式,功能有點像 PHP 的 print_r 或 var_dump。它本身沒什麼奧妙,真正的價值在於「怎麼用得好」。
在認識它之前,多數人查看輸出靠的是 alert,但 alert 只方便顯示字串或數字;一旦你想看物件或陣列的內容,它就會直接顯示成 [object Object],完全看不出所以然。
一、測試頁面 test.html
<html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>console.log test</title> </head> <script type="text/javascript"> var testobj = { 'id': 1, 'content': 'test', 'firstname': function() { document.getElementById('firstname').value = "zhang"; }, 'lastname': function() { document.getElementById('lastname').value = "ying"; } }; <!-- 打印對像 --> console.log(testobj); </script> <body> <input type="text" id='firstname' name="firstname" value=''> <input type="text" id='lastname' name='lastname' value=''> </body> </html>
把整個物件直接丟給 console.log,控制台就會把它展開成可折疊的結構,屬性、方法一覽無遺。
二、用 Chrome 開發者工具檢視

console chrome
這些年我大致是 Chrome 開發者工具與 Firebug 各用一半。Chrome 有個 Firebug 沒有的能力:控制台可以針對 iframe 內部的頁面執行。

chrome iframe console
Firebug 只能把程式碼跑在最外層的父頁面上,而 Chrome 可以直接下拉切換到內層 frame,除錯嵌套頁面的時候差很多。
三、用 Firebug 檢視

firebug console
補充一個實用習慣:想一次看多個值時,與其組字串,不如把多個參數分開傳給 console.log,輸出會自動以空格分隔,可讀性更好;另外在物件上直接點開也能即時展開巢狀結構,比層層 alert 有效率得多。
希望這次的整理對大家的 JavaScript 開發有所幫助。