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

查看:117
本文介绍了javascript开关()或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;
}


推荐答案

您可以使用切换如果你预见到需要添加大量新案例。

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.

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

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