Most efficient way to convert an HTMLCollection to an Array

前端 未结 7 2287
闹比i
闹比i 2020-11-22 13:10

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 a

7条回答
  •  礼貌的吻别
    2020-11-22 13:28

    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.

提交回复
热议问题