Thursday, February 10, 2011

Most efficient way to convert an HTMLCollection to an Array

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?

  • var arr = Array.prototype.slice.call( htmlCollection )
    

    will have the same effect using "native" code.

    Joel Anair : This made my day.
    KooiInc : This doesn't work in IE
    Heath Borders : This fails in IE6.
    From harpo
  • For a cross browser implementation I'd sugguest you look at prototype.js $A function

    copyed from 1.6.1:

    function $A(iterable) {
      if (!iterable) return [];
      if ('toArray' in Object(iterable)) return iterable.toArray();
      var length = iterable.length || 0, results = new Array(length);
      while (length--) results[length] = iterable[length];
      return results;
    }
    

    It doesn't use Array.prototype.slice probably because it isn't available on every browser. I'm afraid the performance is pretty bad as there a the fall back is a javascript loop over the iterable.

0 comments:

Post a Comment