Thankfully, we can convert the arguments object into a true array by using the slice method of the array:
var args = Array.prototype.slice.call (arguments);
For the slice method, the 15.4.4.10 Array.prototype.slice (Start, end) section of ECMAScript 262 has a note:
Copy Code code as follows:
The slice function is intentionally generic; It does not require the IT this value is an Array object. Therefore it can be transferred to the other kinds of the objects for use as a. Whether the slice function can be applied successfully to a host object is implementation-dependent.
Dustin Diaz , author of the Pro JavaScript design Patterns("JavaScript designs"), said:
Copy Code code as follows:
Instead of ...
var args = Array.prototype.slice.call (arguments); Yiwen Fly Note: The next method of a
Do this ...
var args = [].slice.call (arguments, 0); Yiwen Fly Note: The next method two
But do their performance differences really exist? After a personal simple test found:
When the arguments.length is smaller, method two has a slight advantage in performance, while in Arguments.length, the method has a slight advantage.
Last attached method Three, the most old-fashioned way:
Copy Code code as follows:
var args = [];
for (var i = 1; i < arguments.length; i++) {
Args.push (Arguments[i]);
}
However, for the normal, personal advice or use of the second method, but any solution, there is no best, only the most appropriate:
Copy Code code as follows:
var args = [].slice.call (arguments, 0);
There are two reasons:
The general function of the arguments.length is within 10, method two has advantages;
Method Two has less code than the first, at least one bit of byte ^^
How do you convert nodelist (such as: document.getElementsByTagName (' div ')) to an array?
The solution is simple as follows:
Copy Code code 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 is nodelist in IE not allowed to use [].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 are not A JavaScript object.