我正在寻找最有效的方法来重命名(append-1、-2 等)变量(如果它已存在于字符串中)。
所以我保留一个数组”
dupeCheck = [];
一旦我看到一个变量:
var UID;
已经在我的 dupeCheck 数组中,我想立即将 UID 的值附加 -1,
另外,我需要防止第三个重复项变成 string-1-1,而是 string-2..
我看到了这个:Appending the count to duplicates in a javascript string array以前,但这不是我想要的......
有什么聪明的想法吗?我更喜欢 jQuery..
/编辑:
例如:
var dupeUIDCheck = [];
$.each(data[IDS].UIDs[keys], function(keys, val)
{
var currString = val;
switch (key)
{
case "UID":
UID = unquote(currString);
//TODO:
//Detect if multiple UIDs are loaded from a single source, and
//rename them:
dupeUIDCheck.push(UID); //Push current ID onto existing array
//Check if ID exists
?
//If exists rename value of currString, save it in currString
newName = currSting;
break;
case "otherstuff":
//Other vars to parse
break;
}
因此,当我们摆脱“UID”情况时,我想确保它具有唯一的值
最佳答案
您可以将功能包装在函数中以便能够重用它。下面的函数接受一个字符串列表并返回 -1
、-2
等后缀的字符串列表。
function suffixDuplicates( list )
{
// Containers
var count = { };
var firstOccurences = { };
// Loop through the list
var item, itemCount;
for( var i = 0, c = list.length; i < c; i ++ )
{
item = list[ i ];
itemCount = count[ item ];
itemCount = count[ item ] = ( itemCount == null ? 1 : itemCount + 1 );
if( itemCount == 2 )
list[ firstOccurences[ item ] ] = list[ firstOccurences[ item ] ] + "-1";
if( count[ item ] > 1 )
list[ i ] = list[ i ] + "-" + count[ item ]
else
firstOccurences[ item ] = i;
}
// Return
return list;
}
例如输入
[ "Barry", "Henk", "Jaap", "Peter", "Jaap", "Jaap", "Peter", "Henk", "Adam" ]
返回输出
[ "Barry", "Henk-1", "Jaap-1", "Peter-1", "Jaap-2", "Jaap-3", "Peter-2", "Henk-2", "Adam" ]
要查看其实际效果,here是 jsFiddle 示例的链接。
关于jquery - 重命名 Javascript 数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10643933/