Js提示:“;期望一个赋值或函数调用,而看到一个表达式“;,Switch语句

JsHint: "Expected an assignment or function call and instead saw an expression", Switch statement

本文关键字:一个 表达式 语句 Switch 函数调用 Js 赋值 期望 提示      更新时间:2023-09-26

考虑此代码和输出:

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)
    }

输出:

case 1
case 2
case 3

我收到JsHint的投诉说

"Expected an assignment or function call and instead saw an expression"

对于第4、7、10和13行。这是针对包含"&&"的每一行。我通过使用Switch语句中的函数来避免这种情况,例如:

case1:
    function a() {3 + 2 > 3 && (console.log("case 1"))}
    a()
    break;

等等。

我想知道JsHint为什么发出这个警告,以及是否有更好的方法来解决警告问题?

请记住,JSHint只是关于"好"代码的一组意见的体现。在这里,它本质上是在告诉您,它不赞成您使用&&运算符进行控制流。你可能会通过切换到一个简单的if语句来让它高兴起来:

case 1:
    if (3 + 2 > 3) console.log("case 1");
    break;
从逻辑上讲,switch语句与多个If/Else语句类似。

因此:

 switch(x){
    case 1:
        3 + 2 > 3 && (console.log("case 1"));
        break;
    case 4:
        false && console.log("case 4");
 }

相当于:

if (x == 1){
    3 + 2 > 3 && (console.log("case 1"));
} else if (x == 4) {
    false && console.log("case 4");
}

正如您可能看到的,简单地使用逻辑条件通常是没有意义的。你通常想做一些实际的事情,例如任务或职能。JSHint警告您可能会犯错误。

相关文章: