javascript 为什么 JSLint 会抱怨“'return'后出现意外的'else'”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9480692/
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
Why does JSLint complain about "Unexpected 'else' after 'return'"?
提问by Hal
JSLint complains that the following (useless example) code is invalid:
JSLint 抱怨以下(无用的示例)代码无效:
(function (x) {
"use strict";
if (x === 1) {
return 1;
} else if (x === 2) {
return -1;
}
return 0;
}(1));
Error: Problem at line 4 character 9: Unexpected 'else' after 'return'.
return 1;
错误:第 4 行字符 9 出现问题:“返回”后出现意外的“else”。
返回 1;
Is it seriously suggesting that it's bad to use return statements inside an if/else structure?
是否严重暗示在 if/else 结构中使用 return 语句不好?
It thinks this version is fine:
它认为这个版本很好:
(function (x) {
"use strict";
var returnval = 0;
if (x === 1) {
returnval = 1;
} else if (x === 2) {
returnval = -1;
}
return returnval;
}(1));
回答by georg
It's just telling you that else
after return
is superfluous. The following is fine:
它只是告诉你else
之后return
是多余的。以下是好的:
(function (x) {
"use strict";
if (x === 1) {
return 1;
}
if (x === 2) {
return -1;
}
return 0;
}(1));
回答by morph_master_flex
What I've found w/ jslint is that if you adhere to the rules - 50% are ridiculous yet have no negative impact on your code. The other 50% ( or so ) will give you a good benefit. So do it for the other 50%. This particular example forces you to be explicit about the inverse of a condition or similar...instead of letting it be implicit with an else...same applies to if / else I mean.
我使用 jslint 发现的是,如果您遵守规则 - 50% 是荒谬的,但对您的代码没有负面影响。剩下的 50%(左右)会给你带来不错的收益。所以为另外 50% 做这件事。这个特定的例子迫使你明确地说明一个条件的倒数或类似的……而不是让它隐含在 else 中……这同样适用于 if / else 我的意思是。
回答by Jaseem
Its better to have a function always return something as it adds consistency. JSLint is known to be quite strict and hurting programmers' feelings. Cant help it. Personally I think version 1 is fine
最好让一个函数总是返回一些东西,因为它增加了一致性。众所周知,JSLint 非常严格并且会伤害程序员的感受。帮不上忙。我个人认为版本 1 很好