我有一个要迭代的数组,并取决于条件执行任务
我已经用if else完成了这个,然后用Switch进行了尝试,条件是if(1 && 2)(然后执行A)else if(1)(然后执行B)else if(2)(然后执行c)否则,如果(无)(然后执行D)
function showFiletRelateddata(selectedFilter) {
/*if (selectedFilter.length === 0) {
console.log("No data");
} else if (
selectedFilter.includes("Request") &&
selectedFilter.includes("Reservation")
) {
console.log("RequestReservation");
} else if (selectedFilter.includes("Request")) {
console.log("Request");
} else if (selectedFilter.includes("Reservation")) {
console.log("Reservation");
}*/
var filt = selectedFilter;
for (var i = 0; i < filt.length; i++) {
var supp = filt[i];
switch (supp) {
case "Request":
case "Reservation":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
}
如果else正常运行,但是需要对Switch语句进行哪些修改
答案 0 :(得分:1)
function showFiletRelateddata(selectedFilter) {
var filt = selectedFilter;
var supp = ""
for (var i = 0; i < filt.length; i++) { //loop over length of array
supp = supp + filt[i]; // concat elements of array
}
switch (supp) {
case "RequestReservation": // if case contains one of the condition
case "ReservationRequest":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
var a = ["Reservation", "Request"];
var b = ["Request","Reservation"];
var c = ["Reservation"];
var d = ["Request"];
showFiletRelateddata(a);
showFiletRelateddata(b);
showFiletRelateddata(c);
showFiletRelateddata(d);