最近更新: 2013-07-24

JavaScript console

JavaScript console 是一項除錯工具。 完全取代了麻煩的 alert() ,讓開發人員更方便記錄程式執行的各種訊息。

alert() 最大的困擾在於它會暫停程式執行等待使用者確認。 當開發人員要輸出的訊息很多時,不斷跳出的 alert() 視窗實在令人不堪其擾。 而且 alert() 是瀏覽器提供的實作行為,在非瀏覽器環境中沒有 alert() 可用。 console 則不會干擾程式執行,讓你在不需要時感覺不到它的存在。

console is not a standard feature of ECMAScript. However it is widely implemented in most of browsers and you could see the propose in CommonJS. (it may be first provided by Firebug) It is useful for web developer debugging javascript.

Common methods

console 並不是一項標準介面,所以不同瀏覽器實作的方法也不儘相同。 但是目前已知者,都提供下列相同的方法。

  • log(msg | obj, ...) 輸出一行普通的記錄文字。
  • error(msg | obj, ...) 輸出一行標記為 error 的記錄文字。
  • info(msg | obj, ...) 輸出一行標記為 information 的記錄文字。
  • warn(msg | obj, ...) 輸出一行標記為 warning 的記錄文字。
  • dir(obj)
    內識個體。

除了 dir() ,上列方法都可以接受一個以上的參數,而且不限型態。 此外,還支援字串替換用法,例如: console.log("count %d", i)

error, information, warning 等標記差異不會影響程式流程,只是方便開發人員在除錯過程中過濾文字內容。

以 Firefox 為例,按下 Ctrl+Shift+K 召喚網頁主控台。 然後在主控台下方的文字輸入列,或是再按 Shift+F4 召喚速記本。 輸入下列範例程式碼,即可觀察 console 的用途。

console.log("hello console")

var someObject = { str: "Some text", id: 5 };
console.log(someObject);

var car = "Dodge Charger";
console.info("My first car was a %s. The object is: %o.", car, someObject);
MS IE Good methods

MS IE 實作的 console 提供了 assert() 方法。

  • assert(expr, failed_msg)

assert() 是個好東西,可惜其他瀏覽器沒有實作。 所幸自己寫一個很簡單。

if (!console.assert) {
    console.assert = function(expr, failed_msg) {
        if (!expr) console.error(failed_msg);
    }
}

// example of assert()

var s = "abc"; // incorrect word

console.assert(s.length == 5, "excepted length of 'Hello' is 5"); // output an error.


s = "Hello";
console.assert(s.length == 5, "excepted length of 'Hello' is 5"); // no log.
Firefox Good methods
  • time(計時器名稱)
  • timeEnd(計時器名稱)

time() 和 timeEnd() 是配對方法(以計時器名稱為配對),它們提供一組碼錶供開發人員觀察時間間隔。

console.time("timer1")
console.log("test time")
window.alert("Accept some thing...");
console.timeEnd("timer1")

調用 time() 時建立一個計時器,調用 timeEnd() 時停止計時並顯示經過的時間(單位為千分之一秒)。

[10:55:42.987] timer1: 計時器已啟動
[10:55:45.041] test time
[10:55:45.041] timer1: 2054ms
Spec of console

基本上我這個人不使用 ECMAScript 內容以外的 JavaScript 語言功能 。 不過 console 實在好用又很普遍,於是我只好通融一下了。

相關文章
樂多舊網址: http://blog.roodo.com/rocksaying/archives/25402024.html