Search K
Appearance
Appearance
Chrome 开发者工具的 Console 相当好用,最常使用的不外乎是通过 console.log 展示出变量或运算的结果,如果符合预期则皆大欢喜。
但是一旦出现红字幸灾乐祸的告诉我们 " 你出错了!",这对我们来说无疑是一种挫折,在不知如何着手解决错误的时,只能反覆地检查自己的代码,看看是不是有什么奇怪的地方,有时就算停在了错误地方也往往不知是什么意思,会因此花费大量的时间。
前端开发中 Js 常见错误分为两类:代码错误和逻辑错误。
注意
JavaScript 是属于同步的编程语言,如果出现错误就会造成后面的代码无法运行,当红字没有解决时,都有可能造成接下来的代码行错误或是无法继续运行。
解析代码时发生的语法错误。
const 声明的时候必须要赋值,进行初始化;let 或者 const 不允许多次声明同一个变量;var 1a; // Uncaught SyntaxError: Invalid or unexpected token 变量名错误
console.log 'hello'); // Uncaught SyntaxError: Unexpected string 缺少括号
const age;
console.log(age); // Uncaught SyntaxError: Missing initializer in const declaration 常量未赋值 (缺少初始化)
let age = 18;
let age = 21;
console.log(age); // Uncaught SyntaxError: Identifier 'age' has already been declared 重复声明同一个变量console.log(age); // Uncaught ReferenceError: age is not defined 引用了一个不存在的变量
let gender = '男';
console.log(gendr); // Uncaught ReferenceError: gendr is not defined 变量名拼写错误
console.log()= 1; //Uncaught ReferenceError: Invalid left-hand side in assignment 将变量赋值给一个无法被赋值的对象调用一个不终止的递归函数时或者将值传递给超出范围的函数。
let a = new Array(-1); //Uncaught RangeError: Invalid array length 超出有效范围let a = new 123(); //Uncaught TypeError: 123 is not a function
let a;
a.aa(); //Uncaught TypeError: Cannot read property 'aa' of undefined 调用对象不存在的方法
let testArray = ["Test"];
function testFunction(testArray) {
for (var i = 0; i < testArray.length; i++) {
//Uncaught TypeError: Cannot read property 'length' of undefined 传入的参数没有定义
console.log(testArray[i]);
}
}
testFunction();
const age = 18;
age = 21;
console.log(age); //Uncaught TypeError: Assignment to constant variable. 常量被重新赋值了与 url 相关函数参数不正确,主要是 encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape() 和 unescape() 这六个函数。
decodeURI("%2"); //Uncaught URIError: URI malformedeval 函数没有被正确执行。
eval("var a = 1; var b = 2; var c = '3'; var d = '4';"); // Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'".
new eval(); // Uncaught EvalError: Refused to construct a JavaScript URL because it violates the following Content Security Policy directive: "default-src 'self'".