带有switch语句的简单javascript

时间:2012-03-25 13:10:35

标签: javascript

我正在学习javascript,我正在努力让我的案例陈述发挥作用。我们的想法是,您将以调用函数的形式输入1到7之间的任何数字,它会提醒您一周中的某一天。默认值为“非有效日期”。看起来很简单,但我认为我做得对,我感觉它是一个变数问题......

function DayOfTheWeek()

var 1 = DayOfTheWeek;
var 2 = DayOfTheWeek;
var 3 = DayOfTheWeek;
var 4 = DayOfTheWeek;
var 5 = DayOfTheWeek;
var 6 = DayOfTheWeek;
var 7 = DayOfTheWeek;


switch (DayOfTheWeek){
case '1':
alert ("It's Monday");
break;

case 2:
alert ("It's Tuesday");
break;

case 3:
alert ("It's Wednsday");
break;

case 4:
alert ("It's Thursday");
break;

case 5:
alert ("It's Friday");
break;

case 6:
alert ("It's Saturday");
break;

case 7:
alert ("It's Sunday");
break;

default:
alert ("Not a valid day");
break;
}

1 个答案:

答案 0 :(得分:5)

几乎所有代码都是错误的。

你忘了{在定义函数之后和函数结束时}。你想使用一个变量与函数相同的名称(似乎你想这样做)。

变量名称不能以数字开头。

你想要的是:

    function DayOfTheWeek(day) {
        switch(day){
            case 1:
                alert ("It's Monday");
            break;
            case 2:
                alert ("It's Tuesday");
            break;

            case 3:
                alert ("It's Wednsday");
            break;

            case 4:
                alert ("It's Thursday");
            break;

            case 5:
                alert ("It's Friday");
            break;

            case 6:
                alert ("It's Saturday");
            break;

            case 7:
                alert ("It's Sunday");
            break;

            default:
                alert ("Not a valid day");
            break;
        }
    }