0

我有以下代码用于检查数组中是否存在重复项。代码工作正常。但它使用了一个名为 newUniqueArray 的新数组。在不使用新数组的情况下,是否有更好的代码用于此目的?这段代码是否有任何优化可能?

注意:我使用了 jQuery中的inArray和关键字in

<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>
4

2 回答 2

3

如果只想测试字符串数组,可以使用 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;
}​
于 2012-12-12T08:47:57.713 回答
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');
        });
于 2012-12-12T08:37:35.350 回答