Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating array-like objects using forEach, [].forEach.call(...) or Array.prototype.slice.call(...).forEach?

Tags:

javascript

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?

like image 212
Richard Avatar asked Apr 08 '19 08:04

Richard


1 Answers

You could take Array.from and convert the array like object to a real array. Then iterate with some of the array methods.

let array = Array.from(document.getElementsByClassName('dummy'));

array.forEach((e) => {
    console.log(e);
});
<div class = "dummy">Test1</div>
<div class = "dummy">Test2</div>
like image 67
Nina Scholz Avatar answered Oct 26 '22 05:10

Nina Scholz