Code for converting HTMLCollection/NodeList/pseudo array into an array in js

Source: Internet
Author: User

Here, objects that meet the following conditions are called pseudo arrays.
1, with the length attribute
2. Data Storage by index
3. methods such as push and pop with no Array
For example
1. arguments in the function.
2. Use document. forms, Form. elements, Select. options, document. getElementsByName (), document. collection (HTMLCollection, NodeList) obtained by getElementsByTagName () and childNodes/children.
3. Special writing objects, such
Copy codeThe Code is as follows:
Var obj = {};
Obj [0] = "1 ";
Obj [1] = "2 ";
Obj [2] = "3 ";
Obj. length = 3;

They do not have arrays such as push, pop, shift, and join. Sometimes you need to convert these pseudo arrays into real arrays, so that you can use methods such as push and pop. The following is the tool function makeArray.
Copy codeThe Code is as follows:
Var makeArray = function (obj ){
Return Array. prototype. slice. call (obj, 0 );
}
Try {
Array.prototype.slice.call(document.doc umentElement. childNodes, 0) [0]. nodeType;
} Catch (e ){
MakeArray = function (obj ){
Var res = [];
For (var I = 0, len = obj. length; I <len; I ++ ){
Res. push (obj [I]);
}
Return res;
}
}

Test the above three pseudo Arrays:
Copy codeThe Code is as follows:
// Define a function fun. Use makeArray internally to convert its arguments into an array.
Function fun (){
Var ary = makeArray (arguments );
Alert (ary. constructor );
}
// Call
Fun (3, 5 );

// Assume that there are multiple paragraph elements on the page.
Var els = document. getElementsByTagName ("p ");
Var ary1 = makeArray (els );
Alert (ary1.constructor );

// Special js objects (such as jquery objects)
Var obj = {};
Obj [0] = "1 ";
Obj [1] = "2 ";
Obj [2] = "3 ";
Obj. length = 3;
Var ary2 = makeArray (obj );
Alert (ary2.constructor );

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.