Write a weekday()
method that returns "Today is the day of the week*".
function weekDay(){
let string ="今天是星期几"
let date = new Date().getDay()
if (date === 0){
string += "日" ;
} else if (date === 1) {
string += "一" ;
} else if (date === 2) {
string += "二" ;
} else if (date === 3) {
string += "三" ;
} else if (date === 4) {
string += "四" ;
} else if (date === 5) {
string += "五" ;
} else if (date === 6) {
string += "六" ;
}
return string
}
console.log(weekDay())
switch optimization
function weekDay(){
let string ="今天是星期几"
let date = new Date().getDay()
switch (date){
case 0:
string += "日" ;
break ;
case 1:
string += "一" ;
break ;
case 2:
string += "二" ;
break ;
case 3:
string += "三" ;
break ;
case 4:
string += "四" ;
break ;
case 5:
string += "五" ;
break ;
case 6:
string += "六" ;
break ;
}
return string
}
console.log(weekDay())
See here case
is a number, which is consistent with the subscript of the array.
Namely: ['天','一','二','三','四','五','六']
the subscript.
So we can consider using arrays for optimization.
function weekDay() {
let string ="今天是星期几"
let date = new Date().getDay()
let dateArr = [ '天' , '一' , '二' , '三' , '四' , '五' , '六' ];
return string + dateArr [ date ]
}
console.log(weekDay())
Isn't the above code much clearer than switch
statement and statement? if
And even if a week becomes eight days, you only need to modify dateArr
the array.
But what if each of our case
is an irregular string? Then we use objects, each case
for akey
function weekDay() {
let string ="今天是星期几"
let date = new Date().getDay()
let dateObj = { 0:'天' , 1:'一' , 2:'二' , 3:'三' , 4:'四' , 5:'五' , 6:'六' };
return string + dateObj[date]
}
console.log(weekDay())
The above method of using array or object not only improves the readability of the code, but also makes it easier to maintain.