JS converts an object with a numeric property name to an array _javascript tips

Source: Internet
Author: User
Although not very common, we can indeed add attributes with numbers as attribute names to objects:
Copy Code code as follows:

var obj = {};
Obj[0] = 1;
OBJ[1] = 2;

This object is not an array type, so is there any way to convert it to a group type? The jquery code uses Array.prototype.slice to convert this object to an array, but I tried it several times, just not:
Copy Code code as follows:

var obj = {};
Obj[0] = 1;
OBJ[1] = 2;
Alert (Array.prototype.slice.call (obj));

The above code in IE directly under the error, in Firefox, although there is no error, the output is empty. It is said that the conversion has failed. The problem with this built-in approach is better to check it out. ECMA-262, the first two steps of the slice method's execution process are as follows:
Copy Code code as follows:

1. Let A is a new array created as if by the expression new array ().
2. Call the [[[Get]] ' method of ' This object with argument ' length '.

The parameter length is mentioned here. The Obj object has a numeric index but does not have a length property. The problem is this: the slice method does not know the length of the object. Simply modify the code to add the Length property:
Copy Code code as follows:

var obj = {};
Obj[0] = 1;
OBJ[1] = 2;
Obj.length = 2;
Alert (Array.prototype.slice.call (obj));

The output is "1,2" and the copy is successful. Does that mean that you can convert an array if you call the slice method with the numeric index and length property ?

This law is set up in most browsers. However, in IE environment, the collection of DOM elements such as htmlcollection , even with the above features, also complains when calling Slice.

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.