javascript switch() or if()

前端 未结 6 1358
孤独总比滥情好
孤独总比滥情好 2020-12-11 11:37

which would be better if i do this:

if(message == \'redirect\')
{
    is_valid.accepted = true;
}
else if(message == \'invalid id\')
{
    is_valid.accepted          


        
6条回答
  •  [愿得一人]
    2020-12-11 12:12

    If you go with the if statement, I personally prefer setting default values above the if, like this:

    is_valid.accepted = false;
    if(message == 'redirect')
    {
        is_valid.accepted = true;
    }
    

    That way, you always default to a safe behavior that is less likely to break if you add more options later on. Also, you see the default behavior at a glance without having to read through the if-then-else logic. And it's much shorter code.

提交回复
热议问题