[Solved] jQuery .each() function – Which method is optimized? [closed]


I’d use map(), because it’s there for this very purpose (no need for temp array)

var textLinks = $("a").map(function(){
    return $.trim($(this).text());
});

Edit: If I was looking for the fastest solution I’d start with ditching jQuery 😉

var textLinks = (Array.prototype.slice.call(document.links)).map(function(a){ return a.textContent || a.innerText })

Or if you’re concerned about browsers without Array.map use plain old while loop. Looks like a mess, but is FAST.

var textLinks = (function(links, out){ 
    var i = links.length, a; 
    while(a = links[--i]){ out[i] = a.textContent || a.innerText } 
    return out; 
}(document.links,[]))

Added to jsperf test

3

solved jQuery .each() function – Which method is optimized? [closed]