if-else code structure optimization

 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 caseis 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 switchstatement and statement? ifAnd even if a week becomes eight days, you only need to modify dateArrthe array.

But what if each of our caseis an irregular string? Then we use objects, each casefor 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.

Guess you like

Origin blog.csdn.net/m0_53149377/article/details/130147425