js实现今天是星期几的4种写法

发布时间:2019-08-15编辑:脚本学堂
本文分享下,javascript实现的今天是星期几的4种实现方法,供大家学习参考。

方法1,

var str = "";  
var week = new Date().getDay();  
if (week == 0) {  
        str = "今天是星期日";  
} else if (week == 1) {  
        str = "今天是星期一";  
} else if (week == 2) {  
        str = "今天是星期二";  
} else if (week == 3) {  
        str = "今天是星期三";  
} else if (week == 4) {  
        str = "今天是星期四";  
} else if (week == 5) {  
        str = "今天是星期五";  
} else if (week == 6) {  
        str = "今天是星期六";  
}  
<span name="code" class="javascript">alert(str);</span>

方法2,

var str = "今天是星期";  
var week = new Date().getDay();  
switch (week) {  
        case 0 :  
                str += "日";  
                break;  
        case 1 :  
                str += "一";  
                break;  
        case 2 :  
                str += "二";  
                break;  
        case 3 :  
                str += "三";  
                break;  
        case 4 :  
                str += "四";  
                break;  
        case 5 :  
                str += "五";  
                break;  
        case 6 :  
                str += "六";  
                break;  
}  
alert(str);  

方法3,

var a = new Array("日", "一", "二", "三", "四", "五", "六");  
var week = new Date().getDay();  
var str = "今天是星期"+ a[week];  
alert(str);  

方法4,最简单的一种方法:

var str = "今天是星期" + "日一二三四五六".charAt(new Date().getDay());alert(str);