HTML DOM console.assert() 方法


HTML DOM console.assert() 方法僅在提供給它的第一個表示式為 false 時,才用於向控制檯寫入訊息。這些訊息旨在供使用者檢視。該表示式以及要顯示的訊息分別作為 console.assert() 方法的第一個和第二個引數傳送。

語法

console.assert() 方法的語法如下 −

console.assert(assertion,msg);

這裡,斷言是返回布林值 true 或 false 的任意表達式。msg 是一個 JavaScript 字串或物件。斷言應為 false,才能在控制檯上顯示 msg。

示例

我們來看一個 console.assert() 方法的示例 −

<!DOCTYPE html>
<html>
<body>
<h1>console.assert example</h1>
<p>To view the message press F12 on the keyboard and go to the console tab.</p>
<script>
console.assert(document.getElementById("Sample"), "You have no element with ID 'Sample'
in this document");
</script>
</body>
</html>

輸出

這將產生以下輸出 −

在開發者工具的控制檯選項卡中,你將看到以下內容 −

在上例中 −

我們使用 console.assert() 方法和 getElementById() 方法來獲取與之關聯的 ID 為 “Sample” 的元素。因為我們的 HTML 文件中沒有元素,它將返回 false。

第二個引數獲取只有第一個引數返回 false 時才會顯示的訊息。本例中的訊息是 “You have no element with ID ‘Sample’ in this document”,它顯示在控制檯中” −

console.assert(document.getElementById("Sample"), "You have no element with ID 'Sample' in this document");

更新於: 2019 年 8 月 7 日

79 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告