语法错误:返回不在函数中
当在 function 之外调用 return
语句时,会发生 JavaScript 异常 "返回不在函数中"。
¥The JavaScript exception "return not in function" occurs when a return
statement is called outside of a function.
信息
错误类型
什么地方出了错?
¥What went wrong?
return
语句在 function 之外被调用。也许某处缺少大括号?return
语句必须在函数中,因为它结束函数执行并指定要返回给函数调用者的值。
¥A return
statement is called outside of a function. Maybe there are missing curly braces somewhere? The return
statement must be in a function, because it ends function execution and specifies a value to be returned to the function caller.
示例
缺少大括号
¥Missing curly braces
js
function cheer(score) {
if (score === 147)
return "Maximum!";
}
if (score > 100) {
return "Century!";
}
}
// SyntaxError: return not in function
乍一看,大括号看起来是正确的,但此代码片段在第一个 if
语句之后缺少 {
。正确的是:
¥The curly braces look correct at a first glance, but this code snippet is missing a {
after the first if
statement. Correct would be:
js
function cheer(score) {
if (score === 147) {
return "Maximum!";
}
if (score > 100) {
return "Century!";
}
}
也可以看看
¥See also