The following code takes AS3 as an example, and of course, other languages are generally applicable. Let's look at a simple question, how do we get the current day of the week?
A programmer says, too simple, I'll write a paragraph:
The code is as follows |
Copy Code |
var date:date = new Date; if (date.day = 0) { Trace ("Sunday"); } else if (date.day==1) { Trace ("Monday"); } else if (date.day==2) { Trace ("Tuesday"); } else if (date.day==3) { Trace ("Wednesday"); } else if (date.day==4) { Trace ("Thursday"); } else if (date.day==5) { Trace ("Friday"); } else if (Date.day = 6) { Trace ("Saturday"); } |
We run under, yes, the results are correct, a programmer is good. But this time, B programmers defy, say you here a lot of if else statement is really?? The banter of the second and the second, the?/p> of the "Sin-yi" brigade.
code is as follows |
copy code |
var date:d ate = new Date; Switch (date.day) { case 0: trace ("Sunday"); break; case 1: trace ("Monday"); break; case 2: trace ("Tuesday"); break case 3: trace ("Wednesday" ); break; case 4: trace ("Thursday"); break case 5: trace ("Friday" ); break; case 6: trace ("Saturday"); break; } |
B Programmers use a switch statement, and it's a good idea to have a lot more clearly structured than the previous if Else,switch. We can say that the B method is elegant in a.
At this time, C programmer not convinced that the B method or looks very good?? A model?? M?? Qu to pay the illegal glue? Banter the solution:
The code is as follows |
Copy Code |
var date:date = new Date; var weekarr:array=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Trace (Weekarr[date.day]) |
C Programmers cleverly take advantage of the characteristics of the array, the week as a fixed variable, and then you can get the results directly, C code and above, is indeed the least, but also very concise, but this is not the best way? Perhaps some people think that the structure is not very clear, of course, this is the question of the beholder.
We have used 3 different methods to achieve output week, according to the truth has been solved, but people always like toss, at this time, D programmer came, he gave his own code:
The code is as follows |
Copy Code |
var date:date = new Date; var str:string = "Day 123456"; Trace ("Week" +str.charat (Date.day)); |
The fourth method, cleverly exploited by a string of strings, is a method: CharAt is a good way to do it.
Well, we can really end, I know there are other ways to achieve, but, please remember that the code is not the more concise the better, concise sometimes not readable, according to the actual situation, but, toss, will progress!