Home >Web Front-end >JS Tutorial >Code to convert HTMLCollection/NodeList/pseudo array into array in js_javascript skills

Code to convert HTMLCollection/NodeList/pseudo array into array in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:04:171838browse

Here, objects that meet the following conditions are called pseudo arrays
1, have length attributes
2, store data by index
3, and do not have array push, pop and other methods
such as
1. Arguments within the function.
2. Collections (HTMLCollection, NodeList) obtained through document.forms, Form.elements, Select.options, document.getElementsByName(), document.getElementsByTagName(), childNodes/children, etc.
3. Objects with special writing methods, such as

Copy code The code is as follows:

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

They do not have some methods of arrays such as push, pop, shift, join, etc. Sometimes you need to convert these pseudo arrays into real arrays, so you can use push, pop and other methods. The following is the tool function makeArray
Copy code The code is 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; ires.push(obj[i]);
}
return res;
}
}

The above three pseudo Array
Copy code The code is as follows:

//Define a function fun, and use makeArray internally to Its arguments are converted into arrays
function fun(){
var ary = makeArray(arguments);
alert(ary.constructor );
}
//Call
fun(3 ,5);

//Assume there are multiple paragraph elements p 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] = "一";
obj[ 1] = "二";
obj[2] = "三";
obj.length = 3;
var ary2 = makeArray(obj);
alert(ary2.constructor);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn