根据参数返回日期或数字的函数 - Javascript

时间:2017-02-04 12:54:33

标签: javascript function switch-statement

我需要一个函数,当你在一天发送时(例如“星期五”)和一个发送数字的日子(例如“06”)返回一个数字。该函数应该获取包含数字或日期字符串的参数。我尝试过切换,但似乎没有用。

function dayPick(day) {

    let value;

    switch (day) {
        case "friday" || "05":
            if (day === "friday") {
                value = "05";
            } else {
                value = "friday"
            }

            break;
        case "saturday" || "06":
            if (day === "saturday") {
                value = "06";
            } else {
                value = "saturday";
            }

            break;
        case "sunday" || "07":
            if (day === "sunday") {
                value = "07";
            } else {
                value = "sunday";
            }

            break;
    }

    return value;
}

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

这样的方法怎么样?

function dayPick(day) {
    var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    if (isNaN(day)) {
        // Day is literal
        return days.indexOf(day) + 1;
    } else {
        // Day is numeric
        return days[day-1];
    }
}

答案 1 :(得分:2)



function getDay(dayOrNum) {
  const week = ['mon', 'tue', 'wed','thur','fri','sat','sun'];
  
if (typeof dayOrNum === 'number') {
  return week[dayOrNum - 1];
} else {
  return week.indexOf(dayOrNum) + 1;
}
}

console.log(getDay(1)); // output 'mon'
console.log(getDay('mon')); //output 1




答案 2 :(得分:1)

基本上你检查一下

if (day === ("friday" || "05")) {}

仅检查字符串'friday',因为'friday'是一个真值并且检查严格相等。

最好使用支票查看一个值,例如

switch (day) {
    case "friday":
        value = "05";
        break;
    case "05":
        value = "friday";
        break;
    case "saturday":
        value = "06";
        break;
    case "06":
        value = "saturday";
        break;
    case "sunday":
        value = "07";
        break;
    case "07":
        value = "sunday";
        break;
}

或者像

这样的对象
var values = { 
    friday: "05",
    "05": "friday",
    saturday: "06",
    "06": "saturday",
    sunday: "07",
    "07": "sunday"
};

用法

value = values[day];