在JavaScript程序的開(kāi)發(fā)和維護(hù)過(guò)程中,Assert(斷言)是一個(gè)很好的用于保證程序正確性的特性。在具備調(diào)試工具的瀏覽器上,這一特性可以通過(guò)調(diào)用console.assert()來(lái)實(shí)現(xiàn)。比如在以下代碼中,console.assert()語(yǔ)句保證cat對(duì)象的score變量值長(zhǎng)度為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()語(yǔ)句中,第一個(gè)參數(shù)為需要進(jìn)行assert的結(jié)果,正常情況下應(yīng)當(dāng)為true;第二個(gè)參數(shù)則為出錯(cuò)時(shí)在控制臺(tái)上打印的錯(cuò)誤信息。比如,當(dāng)上述例子中score變量的數(shù)組長(zhǎng)度不為3時(shí):
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");
代碼執(zhí)行后,F(xiàn)irebug控制臺(tái)將會(huì)打印錯(cuò)誤信息:

瀏覽器支持
console.assert()在有調(diào)試工具的瀏覽器上支持較好,各大瀏覽器均支持此功能。不過(guò)值得一提的是,F(xiàn)irefox自身并不支持此功能,在Firefox上必須安裝Firebug插件才能使用console.assert()。