What Is The Purpose Of Calling Array.prototype.slice Against A NodeList?
I was looking up how to iterate NodeLists and I came across the following bit of code. var nodesArray = Array.prototype.slice.call(nodeList); nodesArray.forEach(function(node) {
Solution 1:
Iterate a NodeList using forEach method
But I don't understand why we used the slice method ?
You don't have to, you could do this directly
Array.prototype.forEach.call(nodelist, function(value, index) {
...
});
Solution 2:
All these answers are outdated. Actually you can use forEach
on NodeList in modern browsers!
So just use forEach!
Solution 3:
Because slice
returns a copy of any array-like argument as a new array object, which is exactly what we need. We could just as easily use concat
.
Post a Comment for "What Is The Purpose Of Calling Array.prototype.slice Against A NodeList?"