JavaScript中Unexpected end of input 错误
出现“Uncaught SyntaxError Unexpected end of input”错误的主要原因有 3 个:
- 忘记右括号、括号或引号。
-
尝试使用
JSON.parse()
或$.parseJSON
解析空响应。 - 从服务器获取文本/html 响应或根本没有响应并尝试将其解析为 JSON。
错误的最常见原因是忘记了右括号、方括号或引号。
// ⛔️ Uncaught SyntaxError: Unexpected end of input
function sum(a, b) {
return a + b;
// 👆️ forgot closing curly brace
if (true) {
// 👆️ forgot closing curly brace
const arr = ['a', 'b' // 👈️ forgot closing square bracket
const obj = {name: 'Tom' // 👈️ forgot closing curly brace
我们忘记了函数的右花括号和导致错误的 if 语句。
确保我们的代码格式正确,并且我们没有看到会导致语法错误的拼写错误。
我们可以将代码粘贴到在线语法验证器中。 验证器应该能够告诉我们错误发生在哪一行。
在浏览器的开发人员工具中打开控制台,查看在哪一行引发了错误。
错误消息显示在 index.js 文件的第 4 行引发了 SyntaxError
。 根据我的经验,这些信息并非 100% 准确,但有时会有所帮助。
如果我们尝试使用 JSON.parse()
方法解析来自服务器的空响应或空字符串,也会出现“Uncaught SyntaxError Unexpected end of input”。
// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input
console.log(JSON.parse(''));
console.log($.parseJSON(''));
我们解析了一个空字符串并得到了错误。 如果我们的服务器发送空响应并且我们尝试使用
JSON.parse()
解析结果,也会发生这种情况。
为确保我们处理这种情况,可以:
-
将解析逻辑包装在
try/catch
块中 - 确保从我们的服务器返回有效的 JSON 响应
- 如果我们期望一个空的服务器响应,请从代码中删除解析逻辑
我们可以通过打开开发人员工具并单击“网络”选项卡来检查服务器的响应。 如果单击“响应”选项卡,将看到服务器的响应。
下面是一个如何使用 try/catch
块来避免解析时出现“Unexpected end of input”错误的示例。
try {
const result = JSON.parse('');
console.log(result);
} catch (err) {
// 👇️ SyntaxError: Unexpected end of JSON input
console.log('error', err);
}
如果 JSON.parse
函数由于解析无效 JSON 而引发错误,则该错误将作为参数传递给我们可以处理的 catch 函数。
或者,如果我们知道服务器的响应不包含有效的 JSON,我们可以删除对 JSON.parse
函数的调用。
结论
解决“Uncaught SyntaxError Unexpected end of input”错误:
- 添加任何缺少的右括号、括号或引号。
-
不要尝试使用
JSON.parse()
或$.parseJSON
解析空响应。 - 确保我们的服务器返回正确的响应类型,例如 试图解析无效的 JSON 会导致错误。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。