是否可以对多个数组使用开关大小写.indexOf

Is it possible to use switch case for more than one array.indexOf

本文关键字:开关 大小写 indexOf 数组 是否      更新时间:2023-09-26

对于使用javascript 的特定数组,我有一些if条件集

if (activity.indexOf("strategy session") != -1) {
    $("#FoPStrategySession").show();
}
if (activity.indexOf("sessions") != -1) {
    $("#acprojectname").show();
    if (supportmodel == "Level") {
        $(".accombohide").hide();
        $("[title='Test']").val("NA");
        $("[title='Test2']").val("NA");
    }
}
if (activity.indexOf("virtual") != -1) {
    if (supportmodel == "Level") {
        $(".lvl3_consult").hide();
        $("[title='Test']").val("NA");
        $("[title='Test2']").val("NA");
    }
}
if (activity.indexOf("Other") != -1) {
    $("#acactivityother").show();
}

有没有其他方法可以使用switch case或任何其他方法有效地编写此代码?

不需要多个if()switch()语句

您可以降低圈复杂度(现在是7(,最终得到更好的代码。注意,已经重构了一些jQuery选择器$('[title="Test"], [title="Test2"]').val('NA');,并分别使用比较运算符===!==而不是==!=

"一段源代码的圈复杂度是指通过源代码的线性独立路径的数量。"——http://en.wikipedia.org/wiki/Cyclomatic_complexity

还创建了变量,以避免jQuery多次在DOM中搜索相同的选择器。

代码:

var $foPStrategySession = $('#FoPStrategySession'),
    $acprojectname =  $('#acprojectname'),
    $titleTests = $('[title="Test"], [title="Test2"]'),
    $acactivityother = $('#acactivityother'),
    $accombohide = $('.accombohide'),
    $lvl3_consult = $('.lvl3_consult'),
    obj = {
        'strategy session': function () {
            $foPStrategySession.show();
        },
        'sessions': function () {
            $acprojectname.show();
            if (supportmodel === 'Level') {
                $accombohide.hide();
                $titleTests.val('NA');
            }
        },
        'virtual': function () {
            if (supportmodel === 'Level') {
                $lvl3_consult.hide();
                $titleTests.val('NA');
            }
        },
        'Other': function () {
            $acactivityother.show();
        }
    };
    Object.keys(obj).forEach(function (o) {
        if (activity.indexOf(o) !== -1) {
            obj[o]();
        }
    });

首先,您不应该再次查询DOM:

var strategySession = $("#FoPStrategySession");
var acprojectname = $('#acprojectname');
// and so on..

稍后,您将使用上面创建的引用来访问这些DOM元素。

现在,您可以使用Array.prototype.forEach通过switch:简化代码

activity.forEach(function(act) {
    // I suggest you that you lower case each activity
    // to avoid further issues...
    switch(act.toLowerCase())
         case "strategy session":
              strategySession.show();
              break;
         // other cases...
         default:
             throw Error("Not supported activity");
    }
});

旁注:我知道activity数组。否则,您将使用相等运算符检查activity是否是某个特定的string,我的答案应该需要一些重构。如果我错认为activityarray,请评论我的答案