gpt4 book ai didi

javascript - Switch 语句中涉及带条件数组的 Case

转载 作者:行者123 更新时间:2023-12-02 23:50:08 31 4
gpt4 key购买 nike

我有一个要迭代的数组,并根据条件执行任务

我已经使用 if else 完成了此操作,并使用 Switch 进行了尝试。条件是 if (1 && 2) (然后执行 A) else if (1) (然后执行 B) else if (2) (然后执行c) else if (none)(则执行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");
}
}
}

if else 工作正常,但是 Switch 语句需要进行哪些更正

供引用= Javascript switch case with array or strings

最佳答案

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

关于javascript - Switch 语句中涉及带条件数组的 Case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55686158/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com