1. Why is arguments not an array? How to prove it?
Arguments does not have array slice or other methods, so they are not of the array type.
Verification:
FunctionTestargs (){VaRArr = [1, 2, 3]; Console. Log (TypeofArguments. Slice); console. Log (TypeofArr. Slice);} testargs ();
Output:
UndefinedFunction
Of course, you can also prove it in other ways, such as viewing constructor.
2. How to convert to an array?
Use the Slice Method of array as follows:
FunctionArg2arr (){VaRArr =Array. Prototype. Slice. Call (arguments); console. Log (ARR);} arg2arr (1, 2, 3 );
Output: [1, 2, 3]
You can also write it as follows:
Array. Prototype. Slice. Call (arguments, 0)
3. How to use native js to implement your own Slice Method
Array. Prototype. Slice =Function(START, end ){VaRResult =NewArray (); Start= Start | 0; End= End |This. Length;//This points to the called object. When the call is used, the point of this can be changed, that is, to the passed object. This is the key.For(VaRI = start; I <end; I ++) {Result. Push (This[I]);}ReturnResult ;}
4. Is there a toarray method in JS? If not, how can I implement one by myself?
VaR Toarray = Function (S ){ Try { Return Array. Prototype. Slice. Call (s );} Catch (E ){ VaR Arr = []; For ( VaR I = 0, Len = S. length; I <Len; I ++ ){ // Arr. Push (s [I]); Arr [I] = s [I]; // It is said that this is faster than push. } Return Arr ;}}