涉及带条件的数组的Switch语句中的情况

问题描述 投票:0回答:1

我有一个要迭代的数组,具体取决于条件执行任务

我用if else完成了这个并用Switch.And条件是if(1 && 2)(然后执行A)else if if(1)(然后执行B)else if if(2)(然后执行c)else if(无)(然后执行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语句进行更正

对于ref = Javascript switch case with array or strings

javascript arrays switch-statement
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.