(資料圖)
javascript 中的錯(cuò)誤類型:
SyntaxErrorTypeErrorReferenceErrorRangeErrorURLErrorErrorSyntaxError語法錯(cuò)誤
// 當(dāng)您在編寫一個(gè)函數(shù)時(shí)忘記了括號 ,)來括起您的代碼,您將收到一個(gè)SyntaxError錯(cuò)誤function say(text) { return text;}say("shark";// outputUncaught SyntaxError: missing ) after argument list// 當(dāng)函數(shù)參數(shù)和函數(shù)體內(nèi)使用相同的變量名時(shí),您也可能會(huì)遇到此錯(cuò)誤。function say1(text) { let text = "呱呱呱";}// output Uncaught SyntaxError: Identifier "text" has already been declaredTypeErrorTypeError 表示類型錯(cuò)誤。當(dāng)您使用不打算以特定方式使用的東西時(shí),就會(huì)發(fā)生類型錯(cuò)誤。例如,用螺絲刀敲釘子,而不是用錘子。
// a 不是一個(gè)函數(shù)卻被當(dāng)作函數(shù)調(diào)用let a = 1console.log(a()) //outputUncaught TypeError: a is not a function// 對一個(gè)常量進(jìn)行復(fù)制賦值const b = 1b = 2 // you reassign a const type variable again//outputTypeError: Assignment to constant variable.ReferenceErrorReferenceError 表示引用錯(cuò)誤。當(dāng)找不到變量的引用、在變量作用域范圍之外使用變量、使用未聲明的變量時(shí)、在暫時(shí)性死區(qū)期間使用變量時(shí)都會(huì)拋出此錯(cuò)誤。
// 使用未聲明的變量let a = 1console.log(b) // undefined variable used//outputUncaught ReferenceError: b is not defined// 在變量作用域外使用變量const c = 2;if (c > 1) { const d = 3;}console.log(d)// outputUncaught ReferenceError: d is not definedRangeErrorRangeError 表示范圍錯(cuò)誤。將變量設(shè)置在其限定的范圍之外、將值傳遞給超出范圍的方法、調(diào)用一個(gè)不會(huì)終止的遞歸函數(shù)時(shí)就會(huì)拋出此錯(cuò)誤。
URLErrorURIError: malformed URI sequence (Firefox)URIError: URI malformed (Chrome)URIError 表示 URI錯(cuò)誤。當(dāng) URI 的編碼和解碼出現(xiàn)問題時(shí),會(huì)拋出 URIError。JavaScript 中的 URI 操作函數(shù)包括:decodeURI、decodeURIComponent 等。如果使用了錯(cuò)誤的參數(shù)(無效字符),就會(huì)拋出 URIError。
Error嘗試訪問無權(quán)訪問的對象。這很可能出現(xiàn)在使用
<script> console.log(document.getElementById("myframe").contentWindow.document); // Error: Permission denied to access property "document" </script> 更過關(guān)于error的信息,請查閱 JavaScript 錯(cuò)誤參考 - JavaScript | MDN (mozilla.org)