Welcome to my personal blog Xiao Dong's blog
The Array.prototype.slice.call (arraylike,0) method can be used to convert an array of class arrays to facilitate operation in JS what is an array of classes.
var nodelist=document.queryselectorall ("div");
This nodelist is an array of classes.
var nodeList2 = document.getElementById (' ul1 '). ChildNodes;
This nodeList2 is also an array of classes.
We can use nodelist2[0] to fetch the first child element. But when we return false with Console.log (NodeList2 instanceof Array) That means it is not an instance of an array, it is not an array. converting an array through Array.prototype.slice.call (arraylike,0)
Array.prototype.slice represents the slice method in the prototype of an array. Note that this slice method returns an array-type object;
Although the arraylike surface is represented as an array, there is virtually no function of the native array slice, where the call () method is used to modify the function of an incomplete array of Arraylike objects.
var Nodearray = Array.prototype.slice.call (nodelist,0);
var nodeArray2 = Array.prototype.slice.call (nodelist2,0);
At this point, the return of True by calling Console.log (nodeArray2 instanceof Array) indicates that it has been converted to an array object. IE8 and earlier browsers node-type nodes problems
Because IE8 and earlier browsers implemented NodeList as a COM object, we could not use the document.getElementById (' ul1 ') as we would use JavaScript objects. ChildNodes this way get Nod Elist object. Therefore, using Array.prototype.slice.call (nodelist2,0) in IE8 and earlier browsers will cause an error, you must enumerate all the members manually, and the following code is written in all browsers that are compatible
function Converttoarray (nodes) {
var array = null;
try{
array = Array.prototype.slice.call (nodes,0);
} catch (ex) {
array = new Array ();
for (var i=0; len=nodes.length; i<len; i++) {
array.push (nodes[i]);
}
return array;
}