Test for multiple cases in a switch, like an OR (||)
在同一情况下,当您需要测试a或b时,您将如何使用
1 2 3 4 5 6 7 8 | switch (pageid) { case"listing-page" ||"home-page": alert("hello"); break; case"details-page": alert("goodbye"); break; } |
您可以使用Fall Through:
1 2 3 4 5 6 7 8 9 10 | switch (pageid) { case"listing-page": case"home-page": alert("hello"); break; case"details-page": alert("goodbye"); break; } |
因为其他答案解释了如何做而没有实际解释它的工作原理:
当
1 2 3 4 5 6 7 8 9 10 | switch (pageid) { case"listing-page": case"home-page": alert("hello"); break; case"details-page": alert("goodbye"); break; } |
忘记包含
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | switch (someVar) { case 1: someFunction(); alert("It was 1"); // fall through case 2: alert("The 2 case"); // fall through case 3: // fall through case 4: // fall through case 5: alert("The 5 case"); // fall through case 6: alert("The 6 case"); break; case 7: alert("Something else"); break; case 8: // fall through default: alert("The end"); break; } |
您还可以(可选)包括一个
所以在我的第二个例子中,如果
您需要制作两个
控件将从第一个标签掉落到第二个标签,因此它们都将执行相同的代码。
忘了
1 | if(pageid ==="listing-page" || pageid ==="home-page") |
让我们用事例创建几个数组,并用array.prototype.includes()检查它。
1 2 3 4 5 6 7 8 9 10 11 12 | var caseA = ["listing-page","home-page"]; var caseB = ["details-page","case04","case05"]; if(caseA.includes(pageid)) { alert("hello"); } else if (caseB.includes(pageid)) { alert("goodbye"); } else { alert("there is no else case"); } |
你必须改变它!
1 2 3 4 5 6 7 8 | switch (true) { case ( (pageid ==="listing-page") || (pageid === ("home-page") ): alert("hello"); break; case (pageid ==="details-page"): alert("goodbye"); break; } |
使用逗号分隔大小写
1 2 3 4 5 6 7 8 9 | switch (pageid) { case"listing-page","home-page": alert("hello"); break; case"details-page": alert("goodbye"); break; } |