javascript错误_JavaScript错误及其解决方法

javascript错误

JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand at first, and the line numbers given aren’t always helpful either. Wouldn’t it be useful to have a list where you could look to find out what they mean and how to fix them? Here you go!

JavaScript可能是调试的噩梦:一开始它会产生一些错误,很难理解,而且给出的行号也不总是有用。 有一个清单可以帮助您了解它们的含义以及如何修复它们,这对您有用吗? 干得好!

Below is a list of the strange errors in JavaScript. Different browsers can give you different messages for the same error, so there are several different examples where applicable.

以下列出了JavaScript中的奇怪错误。 不同的浏览器可以为您提供相同错误的不同消息,因此有几个不同的示例适用。

如何读取错误? (How to read errors?)

Before the list, let’s quickly look at the structure of an error message. Understanding the structure helps understand the errors, and you’ll have less trouble if you run into any errors not listed here.

在列表之前,让我们快速查看错误消息的结构。 了解结构有助于理解错误,如果遇到此处未列出的任何错误,您的麻烦也将减少。

A typical error from Chrome looks like this:

Chrome的一个典型错误如下所示:

Uncaught TypeError: undefined is not a function

The structure of the error is as follows:

错误的结构如下:

  1. Uncaught TypeError: This part of the message is usually not very useful. Uncaught means the error was not caught in a catch statement, and TypeError is the error’s name.

    未被捕获的TypeError :消息的这一部分通常不是很有用。 未捕获表示错误未在catch语句中catchTypeError是错误的名称。

  2. undefined is not a function: This is the message part. With error messages, you have to read them very literally. For example in this case it literally means that the code attempted to use undefined like it was a function.

    undefined不是函数 :这是消息部分。 对于错误消息,您必须按字面意义阅读它们。 例如,在这种情况下,它的字面意思是代码试图像函数一样使用undefined

Other webkit-based browsers, like Safari, give errors in a similar format to Chrome. Errors from Firefox are similar, but do not always include the first part, and recent versions of Internet Explorer also give simpler errors than Chrome – but in this case, simpler does not always mean better.

其他基于Webkit的浏览器(例如Safari)以类似于Chrome的格式给出错误。 Firefox的错误类似,但并不总是包含第一部分,而且Internet Explorer的最新版本也比Chrome提供的错误更简单-但是在这种情况下,更简单的错误并不总是意味着更好。

Now onto the actual errors.

现在转到实际错误。

未捕获的TypeError:undefined不是函数 (Uncaught TypeError: undefined is not a function)

Related errors: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

相关错误:数字不是函数,对象不是函数,字符串不是函数,未处理的错误:'foo'不是函数,预期的函数

Occurs when attempting to call a value like a function, where the value is not a function. For example:

尝试调用诸如函数之类的值(该值不是函数)时发生。 例如:

var foo = undefined;
foo();

This error typically occurs if you are trying to call a function in an object, but you typed the name wrong.

如果尝试在对象中调用函数,但是键入的名称错误,通常会发生此错误。

var x = document.getElementByID('foo');

Since object properties that don’t exist are undefined by default, the above would result in this error.

由于默认情况下undefined不存在的对象属性,因此上述情况会导致此错误。

The other variations such as “number is not a function” occur when attempting to call a number like it was a function.

尝试像调用数字一样调用数字时,会发生其他变化,例如“数字不是函数”。

How to fix this error: Ensure the function name is correct. With this error, the line number will usually point at the correct location.

如何解决此错误:确保函数名称正确。 遇到此错误,行号通常将指向正确的位置。

未捕获的ReferenceError:分配中的左侧无效 (Uncaught ReferenceError: Invalid left-hand side in assignment)

Related errors: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

相关错误:未捕获的异常:ReferenceError:无法分配给“ functionCall()”,未捕获的异常:ReferenceError:无法分配给“ this”

Caused by attempting to assign a value to something that cannot be assigned to.

尝试将值分配给无法分配的内容。

The most common example of this error is with if-clauses:

此错误的最常见示例是if子句:

if(doSomething() = 'somevalue')

In this example, the programmer accidentally used a single equals instead of two. The message “left-hand side in assignment” is referring to the part on the left side of the equals sign, so like you can see in the above example, the left-hand side contains something you can’t assign to, leading to the error.

在这个例子中,程序员不小心使用了一个单一的等于而不是两个。 消息“分配中的左侧”是指等号左侧的部分,因此,如您在上面的示例中所见,左侧包含无法分配的内容,导致错误。

How to fix this error: Make sure you’re not attempting to assign values to function results or to the this keyword.

如何解决此错误:确保您没有尝试为函数结果或this关键字分配值。

未捕获的TypeError:将圆形结构转换为JSON (Uncaught TypeError: Converting circular structure to JSON)

Related errors: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

相关错误:未捕获的异常:TypeError:JSON.stringify:不是非循环对象,TypeError:循环对象值,value参数中的循环引用不受支持

Always caused by a circular reference in an object, which is then passed into JSON.stringify.

始终由对象中的循环引用引起,然后将其传递到JSON.stringify

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Because both a and b in the above example have a reference to each other, the resulting object cannot be converted into JSON.

由于上例中的ab相互引用,因此无法将结果对象转换为JSON。

How to fix this error: Remove circular references like in the example from any objects you want to convert into JSON.

如何解决此错误:从示例中将要转换为JSON的对象删除循环引用,如示例中所示。

意外的标记 ; (Unexpected token ;)

Related errors: Expected ), missing ) after argument list

相关错误:参数列表后,预期),缺少)

The JavaScript interpreter expected something, but it wasn’t there. Typically caused by mismatched parentheses or brackets.

JavaScript解释器期望了一些东西,但是还没有。 通常由括号或括号不匹配引起。

The token in this error can vary – it might say “Unexpected token ]” or “Expected {” etc.

此错误中的令牌可能会有所不同–可能会显示“意外令牌]”或“预期{”等。

How to fix this error: Sometimes the line number with this error doesn’t point to the correct place, making it difficult to fix.

如何解决此错误:有时出现此错误的行号没有指向正确的位置,因此很难解决。

  • An error with [ ] { } ( ) is usually caused by a mismatching pair. Check that all your parentheses and brackets have a matching pair. In this case, line number will often point to something else than the problem character

    [] {}()错误通常是由于配对不正确引起的。 检查所有括号和方括号是否都具有匹配的对。 在这种情况下,行号通常会指向问题字符以外的其他地方
  • Unexpected / is related to regular expressions. The line number for this will usually be correct.

    意外的/与正则表达式有关。 该行号通常是正确的。
  • Unexpected ; is usually caused by having a ; inside an object or array literal, or within the argument list of a function call. The line number will usually be correct for this case as well

    出乎意料; 通常是由于有; 在对象或数组文字中,或在函数调用的参数列表中。 在这种情况下,行号通常也是正确的

Uncaught SyntaxError:意外的令牌非法 (Uncaught SyntaxError: Unexpected token ILLEGAL)

Related errors: Unterminated String Literal, Invalid Line Terminator

相关错误:未终止的字符串文字,无效的行终止符

A string literal is missing the closing quote.

字符串文字缺少右引号。

How to fix this error: Ensure all strings have the correct closing quote.

如何解决此错误:确保所有字符串都具有正确的结束引号。

未捕获的TypeError:无法读取null的属性'foo',未捕获的TypeError:无法读取未定义的属性'foo' (Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined)

Related errors: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

相关错误: TypeError:someVal为空,无法获取未定义或空引用的属性“ foo”

Attempting to read null or undefined as if it was an object. For example:

尝试读取nullundefined ,就像它是一个对象一样。 例如:

var someVal = null;
console.log(someVal.foo);

How to fix this error: Usually caused by typos. Check that the variables used near the line number pointed by the error are correctly named.

如何解决此错误:通常是由错别字引起的。 检查错误指向的行号附近使用的变量是否正确命名。

未捕获的TypeError:无法将属性'foo'设置为null,未捕获的TypeError:无法将属性'foo'设置为undefined (Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined)

Related errors: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

相关错误: TypeError:someVal未定义,无法设置未定义或空引用的属性“ foo”

Attempting to write null or undefined as if it was an object. For example:

尝试将nullundefined当作对象写入。 例如:

var someVal = null;
someVal.foo = 1;

How to fix this error: This too is usually caused by typos. Check the variable names near the line the error points to.

如何解决此错误:这通常也是由错别字引起的。 检查错误指向的行附近的变量名称。

未捕获的RangeError:超出最大调用堆栈大小 (Uncaught RangeError: Maximum call stack size exceeded)

Related errors: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

相关错误:未捕获的异常:RangeError:超过最大递归深度,递归过多,堆栈溢出

Usually caused by a bug in program logic, causing infinite recursive function calls.

通常由程序逻辑中的错误引起,从而导致无限递归函数调用。

How to fix this error: Check recursive functions for bugs that could cause them to keep recursing forever.

如何解决此错误:检查递归函数中是否有可能导致其永远保持递归的错误。

未捕获的URIError:URI格式错误 (Uncaught URIError: URI malformed)

Related errors: URIError: malformed URI sequence

相关错误: URI 错误: URI序列格式错误

Caused by an invalid decodeURIComponent call.

由无效的encodeURIComponent调用引起。

How to fix this error: Check that the decodeURIComponent call at the error’s line number gets correct input.

如何解决此错误:检查错误行号处的decodeURIComponent调用是否获取正确的输入。

XMLHttpRequest无法加载http:// some / url /。 所请求的资源上没有“ Access-Control-Allow-Origin”标头 (XMLHttpRequest cannot load http://some/url/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource)

Related errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://some/url/

相关错误:跨域请求被阻止:同源策略禁止读取位于http:// some / url /的远程资源

This error is always caused by the usage of XMLHttpRequest.

此错误始终是由XMLHttpRequest的使用引起的。

How to fix this error: Ensure the request URL is correct and it respects the same-origin policy. A good way to find the offending code is to look at the URL in the error message and find it from your code.

如何解决此错误:确保请求URL正确并且遵守同源策略 。 查找有问题的代码的一个好方法是查看错误消息中的URL,然后从您的代码中找到它。

InvalidStateError:尝试使用一个不可用或不再可用的对象 (InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable)

Related errors: InvalidStateError, DOMException code 11

相关错误: InvalidStateError,DOMException代码11

Means the code called a function that you should not call at the current state. Occurs usually with XMLHttpRequest, when attempting to call functions on it before it’s ready.

表示称为函数的代码,您不应在当前状态下调用该函数。 尝试在准备就绪之前调用XMLHttpRequest ,通常会发生在XMLHttpRequest上。

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');

In this case, you would get the error because the setRequestHeader function can only be called after calling xhr.open.

在这种情况下,将出现错误,因为只有在调用xhr.open之后才能setRequestHeader函数。

How to fix this error: Look at the code on the line pointed by the error and make sure it runs at the correct time, or add any necessary calls before it (such as xhr.open)

如何解决此错误:错误所指向的行上查看代码,并确保它在正确的时间运行,或者在它之前添加任何必要的调用(例如xhr.open )。

结论 (Conclusion)

JavaScript has some of the most unhelpful errors I’ve seen, with the exception of the notorious Expected T_PAAMAYIM_NEKUDOTAYIM in PHP. With more familiarity the errors start to make more sense. Modern browsers also help, as they no longer give the completely useless errors they used to.

JavaScript有一些我所见过的最无用的错误,除了PHP中臭名昭著的Expected T_PAAMAYIM_NEKUDOTAYIM 。 随着更多的熟悉,错误开始变得更有意义。 现代浏览器也有所帮助,因为它们不再提供以前完全没有用的错误。

What’s the most confusing error you’ve seen? Share the frustration in the comments!

您看到的最令人困惑的错误是什么? 在评论中分享挫败感!

Want to learn more about these errors and how to prevent them? Detect Problems in JavaScript Automatically with ESLint.

想更多地了解这些错误以及如何防止它们? 使用ESLint自动检测JavaScript中的问题

翻译自: https://davidwalsh.name/fix-javascript-errors

javascript错误

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值