An implementation method of converting htmlcollection/nodelist/pseudo-array into arrays _javascript techniques

Source: Internet
Author: User
Here the objects that meet the following criteria are called pseudo arrays
1, with Length property
2, storing data by index
3, Push,pop and other methods that do not have an array

Such as
1,function within the arguments.
2, through Document.forms,form.elements,select.options,document.getelementsbyname (), document.getElementsByTagName (), A collection (htmlcollection,nodelist), such as Childnodes/children, obtained in other ways.
3, the object of special writing, such as
Copy Code code as follows:

var obj={};
Obj[0] = "one";
OBJ[1] = "two";
OBJ[2] = "three";
Obj.length = 3;

They do not have an array of methods such as push, pop, shift, join, and so on. Sometimes you need to turn these pseudo arrays into real arrays so that you can use methods such as push, pop, and so on. The following is a tool function Makearray
Copy Code code as follows:

var makearray = function (obj) {
Return Array.prototype.slice.call (obj,0);
}
try{
Array.prototype.slice.call (document.documentElement.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;
}
}

The following three pseudo arrays are tested separately
Copy Code code as follows:

//define a function fun, internal use makearray convert it arguments to an array
function fun () {
var ary = Makearray (arguments);
Alert (ary.constructor);
}
//Call
Fun (3,5);


//Suppose there are multiple paragraph elements p
var els = document.getelementsbytagname ("P") on the page;
var ary1 = Makearray (ELS);
Alert (ary1.constructor);


//Special JS object (such as jquery object)
var obj={};
Obj[0] = "one";
Obj[1] = "two";
Obj[2] = "three";
Obj.length = 3;

var ary2 = Makearray (obj);
Alert (ary2.constructor);

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.