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