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)。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在學習ES6的過程中,一路爬行errors
1.let命令
{
let a = 'secret'; function f() { console.log(a); } } f() // 報錯
Uncaught ReferenceError: f is not defined
引用錯誤:f 未定義
- caught 是 catch 的過去分詞形式,過去式形式
- ReferenceError (引用錯誤,reference:談及,查閱)
- defined 有定義的;清晰的;
- const 命令
const PI = 3.1415 PI=3; console.log(PI);
Uncaught TypeError: Assignment to constant variable
類型錯誤:指派 常數 為 變量
- Assignment 指派
- constant 常數
- variable 變量;變化的
function constantize(obj){ console.log(obj); } constantize({a=1,b=0});
Uncaught SyntaxError: Invalid shorthand property initializer
語法錯誤:簡稱的屬性初始化不完整
- Syntax 語法;句法
- Invalid 有病的;傷殘的
- shorthand 簡稱;速記法的;速記
- initializer 初始化