CopyCode The Code is as follows: function test (){
// Convert parameters into an array
VaR ARGs = array. Prototype. Slice. Apply (arguments );
Alert (ARGs );
}
In JavaScript syntax, arguments is an object attribute unique to a function. It is used to reference the actual parameters passed when a function is called. This object is like an array. It has the Length attribute and uses the form of the lower mark to obtain its elements, but it is not a real array object. For more information about arguments objects, see JavaScript authoritative guide.
Therefore, directly calling arguments. Slice () will return an "object doesn't support this property or method" error because arguments is not a real array. The preceding Code calls array. Prototype. Slice. Apply (arguments) to convert the parameter object of the function into a real array. We do not know how to implement the Javascript script engine, but this method is indeed effective and has passed tests in mainstream browsers. On the other hand, we can infer the kinship between the arguments object and the array object. If you often encounter the need to convert the arguments object into an array when writing JavaScript, this technique can help.
This technique comes from the famous douglascrockford. By extension, other prototype methods of array can also be applied to arguments, for example:
VaR arg0 = array. Prototype. Shift. Apply (arguments );
Shift is also an instance method of array, used to obtain and return the first element of the array. Of course, although the above call can be executed, it is purely redundant. It is better to directly call arguments [0. Furthermore, we can apply this technique to many collection objects like arrays, such as array. prototype. slice. apply (document. getelementsbytagname ('div '); unfortunately, ie does not support such calls. Firefox and opera both get the correct results.
The $ A () method added in prototype1.4 is also commonly used to convert arguments into an array. We can see its implementation: Copy code The Code is as follows: var $ A = array. From = function (iterable ){
If (! Iterable) return [];
If (iterable. toarray ){
Returniterable. toarray ();
} Else {
Varresults = [];
For (vari = 0; I <iterable. length; I ++)
Results. Push (iterable [I]);
Returnresults;
}
}
Prototype uses a for loop to construct a new array to ensure maximum compatibility.