如何在不清空HTMLCollection的情况下将其转换为数组? [英] How do I convert a HTMLCollection into an array, without emptying it?
本文介绍了如何在不清空HTMLCollection的情况下将其转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将4个div的HTMLCollection转换为数组,但是我尝试的每种方法似乎都会导致清空该数组.
I am trying to convert an HTMLCollection of 4 divs into an array, but every method I try seems to result in the array being emptied.
<div class="container">
<div class="shape" id="one"></div>
<div class="shape" id="two"></div>
<div class="shape" id="three"></div>
<div class="shape" id="four"></div>
</div>
我尝试过的方法-按照 this上一个问题:
Methods I've attempted - as per this previous question:
var shapesHC = document.getElementsByClassName('shape');
//gives HTMLCollection
var shapesArrCall = [].slice.call(shapesHC);
// returns empty array
var shapesArrHC = Array.from(shapesHC);
// returns empty array
var shapesArrHCSpread = [...shapesHC];
// returns empty array
如果有人能指出我在哪里出问题,我将非常感激.
I'd really appreciate if anyone can point out where I'm going wrong here.
谢谢.
推荐答案
尝试使用此功能:
setTimeout(() => {
this.convertToArray();
});
convertToArray() {
const shapesHC = document.getElementsByClassName('shape');
const shapesArrHCSpread = [...(shapesHC as any)];
console.log(shapesArrHCSpread);
}
这篇关于如何在不清空HTMLCollection的情况下将其转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文