Previously answered questions here said that this was the fastest way:
//nl is a NodeList
var arr = Array.prototype.slice.call(nl);
In benc
faster and shorter :
// nl is the nodelist
var a=[], l=nl.length>>>0;
for( ; l--; a[l]=nl[l] );
Here are charts updated as of the date of this posting ("unknown platform" chart is Internet Explorer 11.15.16299.0):
From these results, it seems that the preallocate 1 method is the safest cross-browser bet.
NodeList.prototype.forEach = Array.prototype.forEach;
Now you can do document.querySelectorAll('div').forEach(function()...)
This is the function I use in my JS:
function toArray(nl) {
for(var a=[], l=nl.length; l--; a[l]=nl[l]);
return a;
}
Some optimizations:
Code (jsPerf):
var arr = [];
for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {
arr[i] = nl[i];
}
The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'
@kangax (IE 9 preview)
Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.
Example:
Array.prototype.slice.call(document.childNodes);