在 JavaScript 程序的開發與維護過程中,斷言(Assert)是保證代碼正確性的一項利器。在具備調試工具的浏覽器上,這一特性可以透過調用 console.assert() 來實現。比如下面這段代碼,就用 console.assert() 確保了 cat 對象 score 變量的長度為 3:
復制代碼 代碼如下:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8,7]);
console.assert(c.score.length==3, "Assertion of score length failed");
在 console.assert() 語句中,第一個參數是需要進行斷言的表達式,正常情況下其結果應當為 true;第二個參數則是斷言失敗時打印到控制台的錯誤信息。舉個例子,當上面示例中 score 數組的長度不為 3 時:
復制代碼 代碼如下:
function cat(name, age, score){
this.name = name;
this.age = age;
this.score = score;
}
var c = new cat("miao", 2, [6,8]);
console.assert(c.score.length==3, "Assertion of score length failed");
代碼執行後,Firebug 控制台便會打印出相應的錯誤信息:

浏覽器支持情況
console.assert() 在帶有調試工具的浏覽器上支持得相當不錯,各大浏覽器基本都提供了對它的支持。值得一提的是,Firefox 自身並不內置這一功能,必須安裝 Firebug 插件之後才能正常使用 console.assert()。