English 中文(简体)
移除 Java稿中的重复内容?
原标题:Removing duplicates from FOR statement in Javascript?

我有:

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 ? At the moment, if 2 href are the same it fixes both ? i.e. 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:

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:

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;
  }
});




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签