Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

if statement - javascript switch() or if()

which would be better if i do this:

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

or i do it this way

switch (message)
{
case 'invalid id':
default:
    is_valid.accepted = false;
    break;
case 'redirect':
    is_valid.accepted = true;
    break;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might use switch if you foresaw needing to add lots of new cases.

If you won't be adding many new cases, I might do, for clarity:

is_valid.accepted = message=='redirect';

(also note that your check for 'invalid id' does nothing)

Nevertheless if you had to add new things, notice how it's good you don't have to repeat yourself don't have to repeat yourself don't have to repeat yourself, also the sexy formatting:

switch (message)
{
    case 'invalid id':
    case 'penguin invasion':
    case 'the internet is down':
    case 'error not enough caffeine':
        is_valid.accepted = false;
        break;

    case 'redirect':
    case 'upvote me':
    case 'vip':
    case 'flamewar':
        is_valid.accepted = true;
        break;

    default:
        is_valid.accepted = false;
        // perhaps log or something
}

Imagine all those ugly else and else-ifs you'd have otherwise.


sidenote: If you had really complicated rules, but still a whitelist-blacklist-on-a-single-flag paradigm, then:

var blacklist = ['invalid id', 'penguin invasion', 'the internet is down' 'error not enough caffeine'];
var whitelist = ['redirect', 'upvote me', 'vip', 'flamewar'];

is_valid.accepted = whitelist.indexOf(message)!=-1;

You might also do this if you wanted to dynamically construct your whitelist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...