使用 JavaScript 将 HTMLCollection 转换为数组

Web*_*001 4 javascript arrays class classname htmlcollection

我想获取带有“Box”类的所有 HTML 元素,然后该集合将其转换为数组,以便我可以通过位置访问每个元素。

这是我制作的代码:

function BoxAppearence() {
    
    var BoxCollection = document.getElementsByClassName("Box");
    console.log(BoxCollection)
    var Box = BoxCollection.split("");
    console.log(Box)
    
    console.log(Box[12])
}

BoxAppearence();
Run Code Online (Sandbox Code Playgroud)

sec*_*can 16

正如评论中提到的,您可以使用 .html 将 HTML 集合转换为数组Array.from()

无论如何,如果将集合转换为数组的唯一原因是能够通过元素的索引/位置访问元素,正如您从下面的代码片段中看到的那样,您也可以使用 HTML 集合来执行此操作(尽管实际上您会使用对象“键”而不是索引)。

function BoxAppearence() {
  var BoxCollection = document.getElementsByClassName("Box");
  var BoxArray = Array.from(BoxCollection);
  
  console.log("### BoxCollection ###");
  console.log("Is 'BoxCollection' an array?", Array.isArray(BoxCollection));
  console.log(BoxCollection);
  console.log(BoxCollection[12])
  console.log('\n\n');
  console.log("### BoxArray ###");
  console.log("Is 'BoxArray' an array?", Array.isArray(BoxArray));
  console.log(BoxArray);
  console.log(BoxArray[12]);
}

BoxAppearence();
Run Code Online (Sandbox Code Playgroud)
<div class="Box">box1</div>
<div class="Box">box2</div>
<div class="Box">box3</div>
<div class="Box">box4</div>
<div class="Box">box5</div>
<div class="Box">box6</div>
<div class="Box">box7</div>
<div class="Box">box8</div>
<div class="Box">box9</div>
<div class="Box">box10</div>
<div class="Box">box11</div>
<div class="Box">box12</div>
<div class="Box">box13</div>
Run Code Online (Sandbox Code Playgroud)