迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 SyntaxError: Illegal return statement 错误

作者:迹忆客 最近更新:2022/12/16 浏览次数:

当在函数外部使用返回语句时,会发生“Illegal return statement”错误。 要解决该错误,请确保仅在命名函数或箭头函数中使用 return 语句。 该语句结束函数的执行并将值返回给调用者。

以下是产生上述错误的示例代码

return 5; // 👈️ return outside function

if (true) { // 👈️ return outside function
  return 10;
}

for (let i = 0; i < 3; i++) { // 👈️ return outside function
  return 15;
}

function example()  // 👈️ missing {
  return true
}

JavaScript 中 SyntaxError- Illegal return statement 错误

Illegal return statement”错误的最常见原因是在函数外部使用返回语句。

if 语句或 for 循环不在函数内部,因此我们不允许在其中使用 return 语句。 相反,我们应该将 if 语句包装在一个函数中。

function test() {
  if (true) {
    return 100;
  }

  return 200;
}

引发错误的另一个常见原因是我们代码中的语法错误。

我们可以通过打开浏览器的控制台或 Node.js 终端来检查代码的哪一行引发了错误。

JavaScript 中 SyntaxError- Illegal return statement 错误

在屏幕截图中,我们可以看到错误是在第 5 行的 index.js 文件中抛出的。

如果我们没有看到任何可能导致错误的语法错误并且 return 语句在函数内部,请将代码粘贴到在线语法验证器中。 验证器应该能够告诉我们错误发生在哪一行。

我们可以将鼠标悬停在波浪形的红线上,以获取有关引发错误原因的更多信息。

要解决“Illegal return statement”错误:

  1. 确保只在函数内部使用 return 语句。
  2. 更正代码中的任何语法错误。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便