[英]Removing duplicates from FOR statement in Javascript?
I have the following 我有以下
var ahrefLength = $('a').length;
for (var i = 0; i < ahrefLength; i++) {
var ahrefUrl = $('a')[i].attr('href');
if(ahrefUrl != '') {
$('a')[i].text('Unique');
}
}
How can I fix this so that no duplicates of "href" appear ? 如何解决此问题,以免出现“ href”的重复项? At the moment, if 2
href
are the same it fixes both ? 目前,如果2
href
相同,则可以同时解决这两个问题? ie I need to ensure that no duplicates 即我需要确保没有重复
var list = {};
$('a[href]').text(function(i,text) {
var href = $(this).attr('href');
if( !(href in list) )
return list[href] = 'Unique';
else
; // what do you want to do with the duplicate?
});
To use a for
statement: 要使用
for
语句:
var list = {};
var a_els = $('a[href]'); // Cache the DOM selection
var len = a_els.length;
for(var i = 0; i < len; i++) {
var a_i = a_els.eq(i);
var href = a_i.attr('href');
if( !(href in list) )
a_i.text(list[href] = 'Unique');
else
; // what do you want to do with the duplicate?
}
You can use an associative array (viz., an object) as a sort of "set" to keep track of what URLs you've already seen: 您可以使用关联数组(即对象)作为一种“集合”来跟踪您已经看到的URL:
var ahrefLength = $('a').length;
var hrefsToSkip = { '': true };
for (var i = 0; i < ahrefLength; i++) {
var ahrefUrl = $('a')[i].attr('href');
if(! hrefsToSkip[ahrefUrl]) {
$('a')[i].text('Unique');
hrefsToSkip[ahrefUrl] = true;
}
}
var hrefIdx = {};
var href = null;
$('a').each(function(i, e) {
href = $(this).attr('href');
if ( href != '' && !hrefIdx[href]) {
$(this).text('Unique');
hrefIdx[href] = true;
}
});
Use jQuery slice:) 使用jQuery slice :)
Demo: http://jsfiddle.net/mhNra/ 演示: http : //jsfiddle.net/mhNra/
Remove all duplicates starting from the end 从头开始删除所有重复项
$( "a" ).each( function() {
$( "a[href=" + $( this ).attr( "href" ) + "]" ).slice( 0, -1 ).remove()
});
Remove all duplicates starting from the first anchor 从第一个锚点删除所有重复项
$( "a" ).each( function() {
var arr = $( "a[href=" + $( this ).attr( "href" ) + "]" );
arr.slice( 1, arr.length ).remove()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.