javascript 未捕获的语法错误:意外的令牌返回 - 仍然没有答案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20725708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:07:33  来源:igfitidea点击:

Uncaught SyntaxError: Unexpected token return - still no answer?

javascriptfunctioncompiler-errorsreturnsyntax-error

提问by Dmitri Zaitsev

So there are dozens of questions with this title, however, all answers I could find seem to mention some hacks working in some specific cases but not being helpful in others. Many are concerned with jQuery or Ajax, yet the problem is pure JavaScript arising at very basic level:

所以这个标题有很多问题,但是,我能找到的所有答案似乎都提到了一些在某些特定情况下有效但在其他情况下没有帮助的技巧。许多人关注 jQuery 或 Ajax,但问题是在非常基础的层面上出现的纯 JavaScript:

function f() {
  false || (return true);
}

This function declaration (without execution) throws

这个函数声明(不执行)抛出

Uncaught SyntaxError: Unexpected token return

Uncaught SyntaxError: Unexpected token return

in Chrome and

在 Chrome 和

SyntaxError: Return statements are only valid inside functions

SyntaxError: Return statements are only valid inside functions

in Safari. However this function doesn't:

在 Safari 中。但是,此功能不会:

function f() {
  false || (a=true);
  return true;
}

Anybody can explain this strange behaviour?

任何人都可以解释这种奇怪的行为吗?

采纳答案by elclanrs

Because returnis not an expression, but it expectsan expression:

因为return不是一个表达式,但它需要一个表达式:

function f() {
  return false || true;
}

回答by thefourtheye

You are using returnstatement in an expression, as an expression, which is not possible as JavaScript engine cannot evaluate it. Thats why it is throwing the error.

return在表达式中使用语句作为表达式,这是不可能的,因为 JavaScript 引擎无法评估它。这就是它抛出错误的原因。