用于检查字符串数组中的重复的更好代码

时间:2012-12-12 08:12:26

标签: javascript jquery

我有以下代码用于检查数组中是否存在重复。代码工作正常。但它使用名为newUniqueArray的新数组。没有使用新阵列,是否有更好的代码用于此目的?这段代码有可能进行任何优化吗?

注意:我使用过jQuery的inArrayin个关键字

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnSave').click(function (e) {
            var reportRecipients = "A, a , b,";
            reportRecipients = reportRecipients.toLowerCase();
            checkDuplicate(reportRecipients);
        });

        function checkDuplicate(reportRecipients) {
            if (reportRecipients.length > 1) {
                var recipientsArray = reportRecipients.split(',');
                var newUniqueArray = [];

                for (a in recipientsArray) {
                    var email = $.trim(recipientsArray[a]);

                    if ($.inArray(email, newUniqueArray) == -1) {
                        newUniqueArray.push(email);
                    }
                }

                if (newUniqueArray.length < recipientsArray.length) {
                    alert('Duplicate Exists');
                }

                return false;
            }
        }
    });
</script>
</head>
<body>
<input name="txtName" type="text" id="txtName" />
<input type="submit" name="btnSave" value="Save" id="btnSave" />
</body>
</html>

2 个答案:

答案 0 :(得分:2)

我看不出为此目的使用jQuery的任何理由:

checkDuplicate = function (reportRecipients) {
    if (reportRecipients.length > 1) {
        var recipientsArray = reportRecipients.split(',');
        for (a in recipientsArray) {
            if(reportRecipients.indexOf(a) != reportRecipients.lastIndexOf(a)){
                return true;
            }
        }
    }
    return false;
}

$('#btnSave').click(function (e) {
            var reportRecipients = "A, a , b,";
            reportRecipients = reportRecipients.toLowerCase();
            if(checkDuplicate(reportRecipients)) alert('Duplicate Exists');
        });

答案 1 :(得分:2)

如果您只想测试字符串数组,可以使用JavaScript对象的属性进行测试。它使用哈希表来查找属性,这比数组迭代更快。

示例:http://jsfiddle.net/jmDEZ/8/

function checkDuplicate(reportRecipients) {
    var recipientsArray = reportRecipients.split(','),
        textHash = {};
    for(var i=0; i<recipientsArray.length;i++){
        var key = $.trim(recipientsArray[i].toLowerCase());
        console.log("lower:" + key);
        if(textHash[key]){
            alert("duplicated:" + key);
            return true;
        }else{
            textHash[key] = true;
        }
    }
    alert("no duplicate");
    return false;
}​
相关问题