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);