JS get day of the week

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.