JavaScript gets the day of the week is very simple, the key is how to obtain in the simplest way, to optimize
Remember when you first learned JavaScript, the teacher told me this:
1 varDate =NewDate (),2D =date.getday (),3str = ' Today is the week ';4 5 if(d = = 0){6str + = ' Day ';7 }8 Else if(d = = 1){9str + = ' One ';Ten } One Else if(d = = 2){ Astr + = ' two '; - } - Else if(d = = 3){ thestr + = ' three '; - } - Else if(d = = 4){ -str + = ' Four '; + } - Else if(d = = 5){ +str + = ' five '; A } at Else if(d = = 6){ -str + = ' Six '; - } - -alert (str);
And after a while the teacher came up with a better way:
1 varDate =NewDate (),2D =date.getday (),3str = ' Today is the week ';4 Switch(d) {5 Case0:6str + = ' Day ';7 Break;8 Case1:9str + = ' One ';Ten Break; One Case2: Astr + = ' two '; - Break; - Case3: thestr + = ' three '; - Break; - Case4: -str + = ' Four '; + Break; - Case5: +str + = ' five '; A Break; at Case6: -str + = ' Six '; - Break; - } - -alert (str);
Maybe after a while I grabbed my head and thought, so many if, case, break, and str ... Wait for the repetition of "words", it can not be simple point? After learning the array and its methods, eh? The following is also possible:
1 var New Date (), 2 D = date.getday (),3 str = ' Today is Week ',4 arr = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ']; 5 str + = arr[d]; 6 7 alert (str);
or something simpler:
1 var str = ' Today is week ' + [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' VI '] [new Date ()]. GetDay ();
Actually the string is also possible:
1 var str = ' Today is week ' + ' Day 123456 '. CharAt (new date (). GetDay ());
Or:
1 var str = ' Today is week ' + ' Day 123456 ' [new Date (). GetDay ()];
JS get day of the week