Fortunately, we can convert the arguments object into a real array through the slice method of the array:
var args = Array.prototype.slice.call(arguments);
For the slice method, ECMAScript 262 15.4. 4.10 Array.prototype.slice (start, end) Chapter has notes:
The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.
Dustin Diaz, the author of "Pro JavaScript Design Patterns" ("JavaScript Design Patterns") once pointed out:
instead of…
var args = Array.prototype.slice. call(arguments); // Yi Fei’s note: hereafter referred to as method one
do this…
var args = [].slice.call(arguments, 0); // Yi Fei’s note: hereafter referred to as method two
But does the performance difference between the two really exist? After a simple personal test, I found:
When arguments.length is small, method two has a slight advantage in performance, but when arguments.length is large, method one has a slight advantage.
Finally, the third method is attached, the most old-fashioned way:
var args = [];
for (var i = 1; i < arguments.length; i ) {
args.push(arguments[i]);
}
However, for normal times, I personally recommend using the second method, but for any solution, there is no best, only the most appropriate:
var args = [].slice.call(arguments, 0);
There are two reasons:
The arguments.length of general functions are within 10, and method two has advantages;
The amount of code in method two is also less than that of the first method, which can at least reduce a little bytes ^^
How to convert NodeList (for example: document.getElementsByTagName('div')) into an array?
The solution is simple as follows:
function nodeListToArray(nodes ){
var arr, length;
try {
// works in every browser except IE
arr = [].slice.call(nodes);
return arr;
} catch(err){
// slower, but works in IE
arr = [];
length = nodes.length;
for(var i = 0; i < length; i ){
arr.push(nodes[i]);
}
return arr;
}
}
Why NodeList cannot be used in IE[ ].slice.call(nodes) method conversion?
In Internet Explorer it throws an error that it can't run Array.prototype.slice.call(nodes) because a DOM NodeList is not a JavaScript object.