javascript switch() 或 if() [英] javascript switch() or if()

查看:22
本文介绍了javascript switch() 或 if()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做会更好:

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

或者我这样做

switch (message)
{
case 'invalid id':
default:
    is_valid.accepted = false;
    break;
case 'redirect':
    is_valid.accepted = true;
    break;
}

推荐答案

如果您预见到需要添加大量新案例,您可以使用 switch.

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';

(另请注意,您对无效 ID"的检查没有任何作用)

(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
}

想象一下所有那些丑陋的 else 和 else-ifs.

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.

这篇关于javascript switch() 或 if()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆