Convert the function parameter arguments into an array in JavaScript.

Source: Internet
Author: User

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.


FunctionTestargs (){VaRArr = [1, 2, 3]; Console. Log (TypeofArguments. Slice); console. Log (TypeofArr. Slice);} testargs ();



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 ;}} 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.