Look at the following code:
function Test () {
To convert an argument to an array
var args = Array.prototype.slice.apply (arguments);
alert (args);
}
Arguments is a function-specific object property (arguments object) in JavaScript syntax that refers to the actual arguments passed when the function is called. This object is very much like an array, has the length property and uses the form of subscript to get its elements, but it is not a true array object. For more information on arguments objects, see the JavaScript Authority Guide.
Therefore, a direct call to Arguments.slice () will return an "Object doesn ' t support this property or method" error, because arguments is not a true array. And the meaning of the above code calling Array.prototype.slice.apply (arguments) is that it converts the parameter object of a function into a true array. How JavaScript scripting engines are implemented is not known, but this approach is indeed valid and is tested in mainstream browsers. On the other hand, the relationship between arguments object and array object can be deduced. This technique can be helpful if you are writing JavaScript and often encounter situations where you need to turn arguments objects into array to handle them.
This technique comes from the famous Douglascrockford. By extension, other prototype methods of array can also be applied to arguments, such as:
var arg0 = Array.prototype.shift.apply (arguments);
Shift is also an instance method of the array that gets and returns the first element of the array. Of course, if the call on the executable, but is purely superfluous, as a direct call arguments[0] to the simple direct.
By extension, we can also apply this technique to many collection objects that resemble an array, such as
Array.prototype.slice.apply (document.getElementsByTagName (' div '));
Unfortunately, IE does not support such a call, both Firefox and Opera can get the right results.
The addition of the $a () method in Prototype1.4 is also used to convert arguments to an array, and we look at its implementation:
var $A = Array.from = function (iterable) {
if (!iterable) return[];
if (Iterable.toarray) {
return Iterable.toarray ();
} else {
var results = [];
for (var i=0; i<iterable.length; i++)
Results.push (Iterable[i]);
return results;
}
}
Prototype uses a For loop to construct the new array to ensure maximum compatibility.