1. 程式人生 > >JavaScript一些判斷寫法

JavaScript一些判斷寫法

例1:if else if else

const fn =(status)=>{
      if(status === 1.1){
        console.log(1);
      }else if(status === 2){
        console.log(2.2);
      }else if(status === 3){
        console.log(3.3);
      }else{
        console.log(4.4);
      }
    }
    fn(3)

例2:三元運算

const fn = (status) => {
      let action = status === 1 ? 
      console.log(1.1) : (status === 2 ? 
      console.log(2.2) : (status === 3 ? 
      console.log(3.3) : console.log(4.4)))
      return action
    }
    fn(2)

例3:物件陣列方法

const actions ={
      '1':[1,1.1],
      '2':[2,2.2],
      '3':[3,3.3],
      'default':[4,4-4]
    }
    const fn = (status) => {
    let action = actions[status] || actions['default']
    console.log(action[0]);
    console.log(action[1]);
    }
    fn(2)
    

例4:switch  case

 const fn = status => {
      switch (status) {
        case 1:
          console.log(1.1);
          break
        case 2:
          console.log(2.2);
          break
        case 3:
          console.log(3.3);
          break
      }
    }
    fn(2)

例5:map

const actions = new Map([
      [1,[1.1,1.2]],
      [2,[2.2,2.3]],
      [3,[3.3,3.4]],
      ['default',[4.4,4.5]]
    ])
    const fn = (status) =>{
      let action = actions.get(status) || actions.get('default')
      console.log(action[0]);
      console.log(action[1]);
    }
    fn(2)