JavaScript SyntaxError: Unexpected token 错误
“Uncaught SyntaxError: Unexpected token”的出现有多种原因:
-
具有指向 HTML 文件而不是 JS 文件的
<script />
标记。 - 从需要 JSON 的服务器获取 HTML 响应。
-
有一个指向不正确路径的
<script />
标签。 - 代码中缺少或多余的括号、括号或逗号。
- 忘记关闭脚本标签。
这是一个如何导致错误的示例,当我们的脚本标签指向一个 html 文件而不是 JS 文件时。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ Uncaught SyntaxError: Unexpected token '<' ⛔️ -->
<script src="index.html"></script>
</body>
</html>
确保我们的脚本标签指向有效路径,并尝试将所有文件仅重命名为小写字母。 如果文件名包含大写字母或特殊字符,有时会导致错误。
该错误的另一个常见原因是忘记关闭脚本标签。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<!-- 👇️ Forgot to close the script tag -->
<script
console.log("Uncaught SyntaxError: Unexpected token '<'");
</script>
</head>
<body></body>
</html>
如果我们在尝试解析 JSON 数据时向服务器发出 HTTP 请求并返回 HTML 响应,也会导致该错误。
要解决此问题,请使用 console.log
记录我们从服务器获得的响应,并确保它是有效的 JSON 字符串且不包含任何 HTML 标记。
我们还可以打开浏览器的开发人员工具,单击网络选项卡并检查响应。
如果我们缺少或多余的括号、括号或逗号,也会出现“Uncaught SyntaxError: Unexpected token”错误。
// ⛔️ SyntaxError: Unexpected token '}'
function sum(a, b) {
return a + b;
}}
第三行有一个额外的大括号,这会导致错误。
我们可以将代码粘贴到在线语法验证器中。 验证器应该能够告诉我们错误发生在哪一行。
或者,我们也可以打开浏览器的控制台并查看行号。 它看起来像 index.js:4。 这意味着错误发生在第 4 行的 index.js 文件中。
这些语法错误很难找到,但一般的经验法则是:
如果我们收到
Uncaught SyntaxError: Unexpected token '<'
(注意<
),我们可能正在尝试阅读一些以<
开头的 HTML 代码。
如果我们的错误消息包含大括号、括号、逗号、冒号等,则我们很可能遇到 SyntaxError
,即代码中有多余或缺少的字符。
错误消息意味着需要一个字符,但提供了另一个字符。 这通常是由于拼写错误。
这是另一个例子。
// ⛔️ Uncaught SyntaxError: Unexpected token ':'
const obj = {
name:: "Tom",
}
我们用 2 个冒号而不是 1 分隔对象中的键和值,导致错误。
如果有额外的逗号,也可能发生这种情况。
// ⛔️ Uncaught SyntaxError: Unexpected token ','
const obj = {
name: 'Tom',,
}
然而,方括号和圆括号是最难追踪的 SyntaxErrors
。
结论
要解决“Uncaught SyntaxError: Unexpected token”错误,请确保:
-
我们没有指向 HTML 文件而不是 JS 文件的
<script />
标记。 - 我们不是从服务器请求 HTML 文件,而是请求 JSON。
-
我们没有指向错误路径的
<script />
标记。 - 我们的代码中没有丢失或多余的括号、括号或逗号。
-
我们没有忘记关闭
<script
标记。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。