javascript - 是否可以对多个 array.indexOf 使用 switch case

标签 javascript jquery arrays performance

我有一些使用 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'); 并使用比较运算符 ===!== 分别代替 ==!=

"The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code." -- 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]();
        }
    });

关于javascript - 是否可以对多个 array.indexOf 使用 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40283458/

相关文章:

javascript - 对通过 [ ] 数组括号访问的属性使用 bind(this)

javascript - 通过 DNS 欺骗规避同源策略

javascript - 如何使用 Jquery 在 ASP.Net 中制作对话框?

javascript - 动态更改交替行颜色

仅当我使用减法时,jQuery 才返回数字

java - 将 String 数组转换为 int 值并将其存储在 int 数组中

javascript - 在 C# 中将 (Javascript)TypedArray 字符串转换为 byteArray 的最佳方法

javascript - 如何设置禁用选项以供评论者和查看者下载、打印和复制

python - numpy中具有不同形状的高效乘法矩阵

javascript - Uncaught ReferenceError : stageCounter is not defined