首頁  >  文章  >  web前端  >  JavaScript中的console.assert()函數介紹

JavaScript中的console.assert()函數介紹

高洛峰
高洛峰原創
2017-02-03 14:31:471619瀏覽

在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()語句中,第一個參數為需要進行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控制台將會列印錯誤訊息:

JavaScript中的console.assert()函數介紹

瀏覽器支援

console.assert()在有偵錯工具的瀏覽器支援較好,各大瀏覽器均支援此功能。不過值得一提的是,Firefox本身並不支援此功能,在Firefox上必須安裝Firebug插件才能使用console.assert()。

更多JavaScript中的console.assert()函數介紹相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn