Home > Article > Web Front-end > Guide to using the getDay method of Date object in javascript_javascript skills
The Date object has a getDay method, which returns the day of the week in a specific date based on local time. The return value ranges from 0 to 6, corresponding to Sunday to Saturday respectively
getDay 0 1 2 3 4 5 6
Day of the week Sunday Monday Tuesday Wednesday Thursday Friday Saturday
When using date-related requirements, you need to convert the value returned by getDay into a day of the week, that is, what day of the week is "this day"? For example, selecting a calendar in the calendar component returns "2014-12-22 Monday".
This is a piece of code that is still running online
This code is judged by multiple if else branches and returns the day of the week. Some students mentioned that it can be optimized using switch
Compared with if/else, the code is much simpler, shorter and clearer. Someone has done statistics that the shorter the code, the shorter the brain's thinking time. Therefore, you will see various people and books advocating and praising "short codes" such as "The Beauty of Short Codes" and "How to Concise Code".
"Code Encyclopedia" mentions using table-driven method to simplify programming
Table-driven method — Table-driven method is a programming pattern (scheme) that searches for information from tables without using logical statements (if and switch). In fact, anything that can be selected through logical statements can be selected through table lookup. For simple cases, it is easier and more straightforward to use logical statements. But as the logic chain becomes more and more complex, the look-up table method becomes more and more attractive.
As mentioned above, tables are used to replace logical statements. Many front-end engineers in JS have tried their best to eliminate statements with expressions since they understood some features of functional languages. For example
1. && replaces single if
2. ?: replace if/else
3. Multiple if/else and switch can also be replaced with multiple "?:"
In addition, you can also use function recursion to eliminate for/while statements. I was addicted to these writing methods at first, but later I found that I couldn't understand them anymore (maybe I still read them less, the brain always naturally converts them into sentences), but in the end I got used to using sentences.
Let’s try replacing the table mentioned in "Code Encyclopedia" with a JS object
Compared with switch, a lot of code has been reduced, but there are still keys 0~6. The value returned by the getDay method starts from 0 just like the JS array index. Therefore, it can be simplified using an array