我使用map-function从几个li元素的rel属性中生成一个逗号分隔的列表。
poiSelectedList = $('#poiList li li.selected').map(function() { return $(this).attr('rel'); }).get().join(',');如何确保我的列表中没有重复项?
发布于 2011-07-31 02:32:10
您可以像这样创建一个缓存:
var cache = [];
poiSelectedList = $('#poiList li li.selected').map(function() {
var rel = $(this).attr('rel');
if(cache.indexOf(rel) === -1) {
cache.push(rel);
return rel;
} else {
return undefined;
}
}).filter(function(a, b) {
return b !== undefined;
}).get().join(',');或者,就像patrick dw建议的那样,一个更简洁的版本:
var cache = [];
$('#poiList li li.selected').each(function() {
var rel = $(this).attr('rel');
if(!$.inArray(rel, cache)) {
cache.push(rel);
}
});
var poiSelectedList = cache.join(); // defaults to ,发布于 2011-07-31 02:34:56
你可以这样做:
var duplicates = {};
poiSelectedList = $('#poiList li li.selected').map(function() {
var rel = $(this).attr('rel');
if (duplicates[rel] !== true){
duplicates[rel] = true;
return rel;
}
}).get().join(',');发布于 2011-07-31 02:31:31
虽然这既不短也不好看,但它应该是一种快速的方法。
var poiSelectedList='';
var tmp;
$('#poiList li li.selected').each(function() { tmp[$(this).attr('rel')]=1; });
var comma=0;
for(var i in tmp) if (tmp.hasOwnProperty(i)){
if(comma){poiSelectedList+=','}else{comma=1}
poiSelectedList+=i;
}https://stackoverflow.com/questions/6885098
复制相似问题