The arguments object in the JavaScript function is converted to an array.

Source: Internet
Author: User

Original article: http://handyxuefeng.blog.163.com/blog/static/45452172201162192755468/

The arguments object in the JavaScript function is converted to an array.

The arguments object in the function is called a "class array" object because it has some features of an array: it has the Length attribute and stores parameters for access using a digital index, but we all know that it is not an array.

Sometimes you need to regard the parameter list as an array so that you can use some methods of the array (such as Concat and splice) for operations. You need to find a way to perform a conversion, there is a similar operation in javascript:

(Function () {var slice = array. Prototype. Slice, aarguments = slice. Apply (arguments) ;}) (10, 20, 30 );

Easy to write:

 
(Function () {var aarguments = []. Slice. Apply (arguments) ;}) (10, 20, 30 );

At this time, aarguments is already a parameter array [10, 20, 30.

The slice method can indeed be used to copy an array, but it is an array method. Directly arguments. Slice () is definitely not. The above method is clever. It utilizes the array features of the arguments object, and then uses the apply method to apply itself to the Slice Method of the array to achieve the effect of converting to the array type.

We can see that an array method like slice can also be used for non-array objects, so I guess the implementation of an array slice method may be similar to this:

 
Array. prototype.Slice = function (START, end) {var ret = [], _ I = Start | 0, _ L = end | this. length; For (; _ I <_ L; _ I ++) {ret. push (this [_ I]);} return ret ;};

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: info-contact@alibabacloud.com 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.