Fortunately, we can use the array slice Method to convert the arguments object into a real array:
Var args = Array. prototype. slice. call (arguments );
For the slice method, section 15.4.4.10 Array. prototype. slice (start, end) in ECMAScript 262 has the following remarks:
Copy codeThe Code is as follows:
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, author of Pro JavaScript Design Patterns, once pointed out:
Copy codeThe Code is as follows:
Instead...
Var args = Array. prototype. slice. call (arguments); // Yunfei Note: method 1
Do this...
Var args = []. slice. call (arguments, 0); // Note: method 2
But is there a real performance difference between the two? After a simple test, I found that:
When arguments. length is small, method 2 has a slight advantage in performance, while method 1 has a slight advantage in arguments. length.
Finally, attach method 3, the oldest method:
Copy codeThe Code is as follows:
Var args = [];
For (var I = 1; I <arguments. length; I ++ ){
Args. push (arguments [I]);
}
However, in general, I suggest using the second method. However, there is no best solution, but the most suitable one:
Copy codeThe Code is as follows:
Var args = []. slice. call (arguments, 0 );
There are two reasons:
The arguments. length of a common function is less than 10, and method 2 has an advantage;
Method 2 has less code than method 1, at least a bit smaller ^
How to convert NodeList (for example, document. getElementsByTagName ('div ') to an array?
The solution is as follows:
Copy codeThe Code is as follows:
Function nodeListToArray (nodes ){
Var arr, length;
Try {
// Works in every browser doesn't 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 can't I use the []. slice. call (nodes) method to convert NodeList in IE?
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.