gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:46:38 24 4
gpt4 key购买 nike

我有以下代码用于检查数组中是否有重复项。该代码运行良好。但它使用了一个名为 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>

最佳答案

如果您只想测试字符串数组,可以使用 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;
}​

关于javascript - 用于检查字符串数组中的重复项的更好代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com