【repost】js 常見錯誤類型

來源:互聯網
上載者:User

標籤:java   pytho   err   define   tween   erro   error:   ber   建構函式   

1)SyntaxError

SyntaxError是解析代碼時發生的語法錯誤

// 變數名錯誤 var 1a; // 缺少括弧 console.log ‘hello‘);

 

(2)ReferenceError

ReferenceError是引用一個不存在的變數時發生的錯誤。

unknownVariable // ReferenceError: unknownVariable is not defined

 

另一種觸發情境是,將一個值分配給無法分配的對象,比如對函數的運行結果或者this賦值。

console.log() = 1 // ReferenceError: Invalid left-hand side in assignment this = 1 // ReferenceError: Invalid left-hand side in assignment

 

上面代碼對函數console.log的運行結果和this賦值,結果都引發了ReferenceError錯誤

(3)RangeError

RangeError是當一個值超出有效範圍時發生的錯誤。主要有幾種情況,一是數組長度為負數,二是Number對象的方法參數超出範圍,以及函數堆棧超過最大值。

new Array(-1) // RangeError: Invalid array length (1234).toExponential(21) // RangeError: toExponential() argument must be between 0 and 20

 

(4)TypeError

TypeError是變數或參數不是預期類型時發生的錯誤。比如,對字串、布爾值、數值等原始類型的值使用new命令,就會拋出這種錯誤,因為new命令的參數應該是一個建構函式。

new 123 //TypeError: number is not a func var obj = {}; obj.unknownMethod() // TypeError: undefined is not a function

 

上面代碼的第二種情況,調用對象不存在的方法,會拋出TypeError錯誤。

(5)URIError

URIError是URI相關函數的參數不正確時拋出的錯誤,主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()這六個函數。

decodeURI(‘%2‘) // URIError: URI malformed

 

(6)EvalError

eval函數沒有被正確執行時,會拋出EvalError錯誤。該錯誤類型已經不再在ES5中出現了,只是為了保證與以前代碼相容,才繼續保留。

以上這6種派生錯誤,連同原始的Error對象,都是建構函式。開發人員可以使用它們,人為建置錯誤對象的執行個體。

new Error("出錯了!"); 
new RangeError("出錯了,變數超出有效範圍!");
new TypeError("出錯了,變數類型無效!");

 

上面代碼錶示建立錯誤對象的執行個體,實質就是手動拋出錯誤。可以看到,錯誤對象的建構函式接受一個參數,代表錯誤提示資訊(message)。

  

【repost】js 常見錯誤類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.