使用$.map查找对象中的重复字符串

Finding duplicate strings in object using $.map

本文关键字:字符串 对象 map 查找 使用      更新时间:2023-09-26

从下面的代码中,我期望elist将只包含er中的每个字符串一次。我的意思是elist会有er的唯一值。但我没有得到唯一的字符串在elist。怎么了?

i = 0; 
elist = "";
$.map(er, function(value, key){                          
    if ( isDuplicate(value, er, i) < 0 ) {
        elist += value;  
    }
    $("#"+key).addClass('has-error');
    i += 1;
});
function isDuplicate(str, er_, offset){
    j = 0; 
    return_val = -1
    $.map(er_, function(value, key){
        alert(j +'>'+offset+'------'+value+'=='+str);
        if ( j > offset && value == str){
            return_val = j;
            alert('matched');
        }
        j += 1;
    });
    return return_val;
}

您可以使用更简单的代码:

var arr=[];
$.map(er, function(value, key){           
    if   ( arr.indexOf(value) == -1 ) 
   {arr.push(value);}
});
alert(arr.join());
http://jsfiddle.net/7cohow41/3/