在JavaScript日志中,开发者经常会遇到各种错误。以下是一些常见的错误类型及其简要描述:
语法错误(SyntaxError):
function say(text) { return text; } say('shark');
输出 Uncaught SyntaxError: missing ) after argument list
。引用错误(ReferenceError):
console.log(a);
输出 Uncaught ReferenceError: a is not defined
。类型错误(TypeError):
let a = '123'; let result = a + 4;
输出 Uncaught TypeError: Cannot read property 'toString' of undefined
。范围错误(RangeError):
var a = new Array(-1);
输出 Uncaught RangeError: Invalid array length
。URI错误(URIError):
encodeURI()
或 decodeURI()
。decodeURI('%2');
输出 Uncaught URIError: URI malformed
。错误使用 ==
而不是 ===
:
==
运算符执行类型强制转换,而 ===
运算符检查严格相等性,不进行类型转换。console.log(0 == '0');
输出 true
,但 console.log(0 === '0');
输出 false
。变量提升问题:
console.log(myVar); let myVar = 'value';
输出 undefined
。this
指向问题:
this
关键字的指向是动态的,可能会导致意外的行为。var name = "John"; var person = { name: "Bob", sayName: function () { console.log("name", this.name); }}; var sayName = person.sayName; sayName();
输出 John
。异步代码处理不当:
async/await
或 then/catch
)会导致意外行为和错误。function fetchData() { return fetch('https://api.example.com/data'); } const data = fetchData();
。内存泄漏:
theThing
对象的引用未清除,导致内存泄漏。。了解这些常见错误及其解决方法,可以帮助开发者在编写和调试JavaScript代码时更加高效和准确。