[英]JsHint: “Expected an assignment or function call and instead saw an expression”, Switch statement
Consider this code and output: 考虑以下代码和输出:
var f = function(x){
switch(x){
case 1:
3 + 2 > 3 && (console.log("case 1"));
break;
case 2:
4 + 2 < 20 && (console.log("case 2"));
break;
case 3:
true && console.log("case 3");
break;
case 4:
false && console.log("case 4");
}
};
for(var i = 0; i < 6; i++){
f(i)
}
Output: 输出:
case 1
case 2
case 3
I get a complaint from JsHint saying 我收到JsHint的抱怨说
"Expected an assignment or function call and instead saw an expression"
for line 4, 7, 10 and 13. That is for each line containing "&&". 代表第4、7、10和13行。也就是每个包含“ &&”的行。 I managed to escape this by using functions within the Switch statement, for example:
我设法通过使用Switch语句中的函数来对此进行转义,例如:
case1:
function a() {3 + 2 > 3 && (console.log("case 1"))}
a()
break;
etc. 等等
I wonder why JsHint makes this warning and if there is a better way to solve the problem with the warnings? 我想知道为什么JsHint发出此警告,以及是否有更好的方法来解决警告问题?
Keep in mind that JSHint is just the embodiment of a set of opinions about what "good" code is like. 请记住,JSHint只是关于“好”代码是什么样的观点的体现。 Here, it's essentially telling you that it disapproves of your use of the
&&
operator for control flow. 在这里,它实际上是在告诉您,它不赞成使用
&&
运算符进行控制流。 You could probably make it happy by switching to a simple if
statement: 您可以通过切换到简单的
if
语句来使其高兴:
case 1:
if (3 + 2 > 3) console.log("case 1");
break;
A switch statement is, logically, like multiple If/Else statements. 从逻辑上讲,switch语句类似于多个If / Else语句。
So: 所以:
switch(x){
case 1:
3 + 2 > 3 && (console.log("case 1"));
break;
case 4:
false && console.log("case 4");
}
is the equivalent of: 等价于:
if (x == 1){
3 + 2 > 3 && (console.log("case 1"));
} else if (x == 4) {
false && console.log("case 4");
}
As you might be able to see, simply using a logical condition doesn't generally make sense. 如您所见,仅使用逻辑条件通常没有任何意义。 You usually want to actually do something, eg assignment or function.
通常,您通常想做一些事情,例如赋值或函数。 JSHint is warning you of a likely mistake.
JSHint向您警告可能的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.