The DOM usually returns a NodeList
for most operations like getElementsByTagName
.
Although a NodeList
almost feels like an array, it is not. It has a length
property like an array does, and a method item(index)
to access an object at the given index (also accessible with the [index]
notation), but that's where the similarity ends.
So to be able to use the wonderful array methods without rewriting them all for a NodeList
, the above line is useful.
Another use of converting it to an array is to make the list static. NodeLists are usually live, meaning that if document changes occur, the NodeList object is automatically updated. That could cause problems, if a jQuery object returned to you kept changing right under your nose. Try the following snippet to test the liveness of NodeLists.
var p = document.getElementsByTagName('p');
console.log(p.length); // 2
document.body.appendChild(document.createElement('p'));
// length of p changes as document was modified
console.log(p.length); // 3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…