HTML DOM console.error() 方法


HTML DOM console.error() 方法用於在控制檯中寫入錯誤訊息。此方法對測試和除錯非常有用。

語法

以下為 console.error() 方法的語法 −

console.error(console.error(message))

在此,message 是 JavaScript 字串或物件。這是必需的引數值。

範例

我們來看一個 HTML DOM console.error() 方法的範例 −

<!DOCTYPE html>
<html>
<body>
<h1>console.error() Method</h1>
<p>Click the below button to write object as error message on the console</p>
<button type="button" onclick="errMessage()">ERROR</button>
<script>
   function errMessage(){
      var errObj = { Message:"ERROR has been caused",Value:"NEGATIVE"};
      console.error(errObj);
   }
</script>
<p>Press F12 key to view the error message in the console </p>
</body>
</html>

輸出

將產生以下輸出 −

單擊 ERROR 按鈕並在開發工具控制檯選項卡中檢視 −

在上述範例中 −

我們首先建立了一個 ERROR 按鈕,使用者單擊時將執行 errMessage() 函式 −

<button type="button" onclick="errMessage()">ERROR</button>

errMessage() 方法建立一個包含成員 訊息 及其相應值的 物件。然後將此物件作為引數傳遞給控制檯物件的 error() 方法。console.error() 方法將在控制檯上將物件列印為錯誤訊息 −

function errMessage(){
   var errObj = { Message:"ERROR has been caused",Value:"NEGATIVE"};
   console.error(errObj);
}

更新日期:2019 年 8 月 8 日

71 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告