I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don’t completely understand how it works:
[].slice.call(document.querySelectorAll('a'), 0)
So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?
The bit I don’t understand is the call. How does that convert document.querySelectorAll('a') from a NodeList to a regular array?
What’s happening here is that you call
slice()as if it was a function ofNodeListusingcall(). Whatslice()does in this case is create an empty array, then iterate through the object it’s running on (originally an array, now aNodeList) and keep appending the elements of that object to the empty array it created, which is eventually returned. Here’s an article on this.EDIT:
That’s not right.
[].slicereturns a function object. A function object has a functioncall()which calls the function assigning the first parameter of thecall()tothis; in other words, making the function think that it’s being called from the parameter (theNodeListreturned bydocument.querySelectorAll('a')) rather than from an array.