我正在尝试将 4 个 div 的 HTMLCollection 转换为数组,但我尝试的每种方法似乎都会导致数组被清空。
<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 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
如果有人能指出我在这里出错的地方,我将不胜感激。
谢谢。
最佳答案
尝试使用这个:
setTimeout(() => {
this.convertToArray();
});
convertToArray() {
const shapesHC = document.getElementsByClassName('shape');
const shapesArrHCSpread = [...(shapesHC as any)];
console.log(shapesArrHCSpread);
}
关于javascript - 如何将 HTMLCollection 转换为数组而不清空它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153968/