0

Haii so I've recently used converting HTMLCollection to array in order to use the filter method and that by doing Array.prototype.slice.call(htmlcollection).filter(...); from a stackoverflow answer but I can't figure out 2 things:

  1. Array.prototype.slice(htmlcollection).filter(...); won't work
  2. How can a HTMLCollection use an array method

Finally I'd like to create this behavior in my own classes so I can call Array.prototype.slice.call(new MyClass()).filter(...);

Thanks in advance for your generous contribution and time

Jhon
  • 135
  • 8
  • 2
    #1 Because `slice` doesn't take the array to slice as an argument. #2 HTMLCollection is an iterable object, the language is designed so, that iterable objects can be sliced. ES6+ has [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method, maybe you don't need to implement your own class for this ..? – Teemu Jul 30 '20 at 07:32
  • @Teemu Why htmlcollection.slice() won't work?? if HTMLCollection is an iterable – Jhon Jul 30 '20 at 07:38
  • Because [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) object doesn't have `slice` method. The key why `Array.prototype.slice.call(htmlcollection)` works is [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), which sets the collection as `this` to `slice`, and the slicing can be performed. – Teemu Jul 30 '20 at 07:43
  • So you're saying doing [1, 2, 3, 4].slice() is different from Array.prototype.slice.call([1, 2, 3, 4]) ?? – Jhon Jul 30 '20 at 07:47
  • Basicly yes, the former uses the method from the array instance directly, in the latter, the method is used statically from the prototype. Please read what is written about `call` at MDN, the article is linked in my comment above. – Teemu Jul 30 '20 at 07:50

1 Answers1

2

You can use the Array.from() method

Reference here

Odunsi
  • 421
  • 1
  • 4
  • 16