We can achieve iteration on array-like objects using both of the following methods:
let arrayLike = document.getElementsByClassName('dummy');
[].forEach.call(arrayLike, (e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
Or using slice to convert array-like objects to array first:
let arrayLike = document.getElementsByClassName('dummy');
Array.prototype.slice.call(arrayLike).forEach((e) => {
console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
Which one is more preferrable and why in the case where I need not the converted array-like object? The first one feels a little 'hacky' but the second one feels more readable. Or are both just the same, meaning both will do just fine?
[...arrayLike].forEach()orArray.from(arrayLike)for...of