Most efficient way to convert an HTMLCollection to an Array

前端 未结 7 2249
闹比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:24

    This is my personal solution, based on the information here (this thread):

    var Divs = new Array();    
    var Elemns = document.getElementsByClassName("divisao");
        try {
            Divs = Elemns.prototype.slice.call(Elemns);
        } catch(e) {
            Divs = $A(Elemns);
        }
    

    Where $A was described by Gareth Davis in his post:

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

    If browser supports the best way, ok, otherwise will use the cross browser.

提交回复
热议问题