我的javascript包含重复的代码,可以减少

Does my javascript contain repetitive code that can be reduced?

本文关键字:代码 javascript 包含重 我的      更新时间:2023-09-26

我觉得这里有太多重复的代码。我所做的就是为URL中的字符串做一个基本的正则表达式匹配。如果找到了匹配,我就找到了一个班级。Index、.grid、.type)并添加活动类。这只是我的主导航,试图使它有一些动态。然而,我觉得有一种更有效的方法来编写此代码。如有任何帮助,不胜感激。

$( document ).ready(function() {
var myLocation = window.location;
var convertURL = new String(myLocation);
var index = /index/i;
var grid = /grid/i;
var type = /type/i;
var urlIndex = convertURL.match(index);
var urlGrid = convertURL.match(grid);
var urlType = convertURL.match(type);
if(urlIndex) {
$('.index').addClass('active'); 
}else if(urlGrid) {
$('.grid').addClass('active');
}else if(urlType) {
$('.type').addClass('active');
    }
});
$(function(){
    ["index", "grid", "type"].forEach(function(term){
        if(new RegExp(term, "i").test(location.href)) 
            $("." + term).addClass("active"); 
    });
});
$(document).ready(function () {
    // use single var per function, good for minimizing and other stuff
    var
    i,
    // new string literal, not String object
    convertURL = '' + window.location,
    // the array of strings keeps only the difference from the repetitive code
    classes = ['index', 'grid', 'type'],
    // using functions with proper arguments reduces repetitivness
    matches = function (regex) {
        return convertURL.match(new RegExp(regex, 'i'));
    }
    // var
    ;
    // always use += instead of ++ -> makes for clear intention
    for (i = 0; i < classes.length; i += 1) {
        if (matches(classes[i])) {
            // returning out of this function stops iteration
            return $('.' + classes[i]).addClass('active');
        }
    }
});