search

Home  >  Q&A  >  body text

javascript - switch...case...

export const setID = (v) => {
  console.log('执行setID',v);
  let l = v.length;
  switch(l)
  {
    case l < 6 :
      console.log('qq');
      break;
    default:
      console.log('11111');
  }

}

v is the incoming string. The first console of this code is executed normally, and the second console is not executed under any circumstances. Now I am sure that there is something wrong with my switch...case.... Please tell me what the problem is

typechotypecho2695 days ago955

reply all(3)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-28 09:30:02

    Change it to the following

    const setID = (v) => {
      console.log('执行setID',v);
      let l = v.length;
      switch(l < 6)
      {
        case true :
          console.log('qq');
          break;
        default:
          console.log('11111');
      }
    
    }

    But you can definitely use an if statement:

    if (l < 6) {
        console.log("qq");
    } else {
        console.log("1111");
    }

    According to the original writing, it should be whether l and l < 6 are equal. l is an integer, indicating the length of the string. l<6 is a Boolean value. Integers and Boolean values ​​are not congruent. , so the default statement will always be used;
    The misunderstanding of the original writing method: it is not that the case statement will be executed if it is true, but the content in the switch expression l and the content after the case statement l< Matches only when 6 are congruent; assuming v="111", then l=3 l<6 is true, but 3!==true, so the default statement is used.

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-28 09:30:02

    Are you sure your l is less than 6?

    switch(n)
    {
    case 1:
      执行代码块 1
      break;
    case 2:
      执行代码块 2
      break;
    default:
      n 与 case 1 和 case 2 不同时执行的代码
    }

    reply
    0
  • 代言

    代言2017-06-28 09:30:02

    export const setID = (v) => {
      console.log('执行setID',v);
      let l = v.length;
      switch(true)
      {
        case l < 6 :
          console.log('qq');
          break;
        default:
          console.log('11111');
      }
    
    }

    reply
    0
  • Cancelreply