Test for multiple cases in a switch, like an OR (||)

后端 未结 6 635
暗喜
暗喜 2020-11-28 01:16

How would you use a switch case when you need to test for a or b in the same case?

switch (pagei         


        
6条回答
  •  庸人自扰
    2020-11-28 01:54

    Forget switch and break, lets play with if. And instead of asserting

    if(pageid === "listing-page" || pageid === "home-page")
    

    lets create several arrays with cases and check it with Array.prototype.includes()

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

提交回复
热议问题