关于 document.getElementsByTagName

nodelist 并不是数组

今天在写程序的时候发现,document.getElementsByTagName('') 返回的结果并不是我一直认为的数组。之前一直使用 jquery 或者其他lib,并没有发现这个细节。 在 chrome 浏览器中调试的时候发现返回的结果不能调用 forEach 方法,这时候才意识到这个结果可能不是个数组。

> document.getElementsByTagName('img') instanceof Array
> false
> [] instanceof Array
> true

查了下 w3school 中的解释

getElementsByTagName() 方法返回节点列表。节点列表是一个节点数组(nodelist)。

而 nodelist 和 array 是不同的东西,下面是各自的继承关系

myArray --> Array.prototype --> Object.prototype --> null
myNodeList --> NodeList.prototype --> Object.prototype --> null

所以nodelist虽然具有一些 array 的特征,但它并不是 array。

如何遍历

用基本的 for 来遍历 nodejs

var length = nodelist.length;
for(var i=0; i<length; i++){
   var node = nodelist[i]
}

注意不能用 for...in

转化成数组

下面的方法可以将 nodelist 转化成 array

Array.prototype.slice.call(nodelist);

参考

NodeList

原文地址:https://www.cnblogs.com/Rexxar/p/5564365.html