Javascript tips for converting objects with numeric attribute names into arrays _ javascript

Source: Internet
Author: User
In js, objects with numeric attribute names are converted into arrays. Although not commonly used, we can indeed add attributes with numbers as attribute names to objects, although they are not commonly used, however, we can add the attribute named "Number" to the object:

The Code is as follows:


Var obj = {};
Obj [0] = 1;
Obj [1] = 2;


This object is not an array type. Is there any way to convert it to an array type? In jQuery code, Array. prototype. slice is used to convert this object into an Array. However, I tried it several times, but it won't work:

The Code is as follows:


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


The above Code directly reports an error in IE. Although no error is reported in Firefox, the output content is empty. That is to say, the conversion fails. It is best to check the problem of this built-in method. ECMA-262The first two steps of the slice method execution process are as follows:

The Code is as follows:


1. Let A be a new array created as if by the expression new Array ().
2. Call the [[Get] method of this object with argument "length ".


The length parameter is mentioned here. Although the obj object has a digital index, it does not have the length attribute. The problem is that the slice method does not know the object length. Simply modify the code and add the length attribute:

The Code is as follows:


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


The output content is "1, 2". Copied successfully. Does that explain,This can be converted to an array as long as the slice method has the numeric index and length attributes.What about it ?.

This law is true in most browsers. However, in the IE environmentHtmlCollectionEven if such a DOM Element Set has the preceding features, it reports an error when calling slice.

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: 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.