我是学习编程(特别是JavaScript)的初学者。我在学习编码时遇到了一个小问题。当我使用switch语句解决一个问题时,它会产生正确的输出。



var dateNow = 3;
var dateSuffix;

switch (dateNow) {
  case 1:
  case 21:
  case 31:
    dateSuffix = "st";
    break;
  case 2:
  case 22:
    dateSuffix = "nd";
    break;
  case 3:
  case 23:
    dateSuffix = "rd";
    break;
  default:
    dateSuffix = "th";
    break;
}

console.log("Today is the " + dateNow + dateSuffix + " day.");
    





但是当我对if else语句执行相同操作时,输出错误。



var dateNow = 3;
var dateSuffix;

if (dateNow == 1 || 21 || 31) {
  dateSuffix = "st";
} else if (dateNow == 2 || 22) {
  dateSuffix = "nd";
} else if (dateNow == 3 || 23) {
  dateSuffix = "rd";
} else {
  dateSuffix = "th";
}

console.log("Today is " + dateNow + dateSuffix + " day of the month...");





任何人都可以指出我的if语句存在的问题吗?

最佳答案

您不能使用dateNow == 1 || 21 || 31

您需要使用[1,21,31].includes(dateNow)

dateNow == 1 || dateNow == 21 || dateNow == 31



var dateNow = 3;
var dateSuffix;

if ([1,21,31].includes(dateNow)) {
  dateSuffix = "st";
} else if ([2,22].includes(dateNow)) {
  dateSuffix = "nd";
} else if ([3,23].includes(dateNow)) {
  dateSuffix = "rd";
} else {
  dateSuffix = "th";
}

console.log("Today is " + dateNow + dateSuffix + " day of the month...");

09-11 19:54