前言
啥都是从前言开始说的。之前一直以为类数组就是HTML集合,今天才发现其实不是的,是我理解偏了。
定义
啥叫类数组?
类数组:有length属性,但是不是数组,没有数组的方法,比如forEach、map、slice。不过其实想要它们能拥有数组的方法也不是不可以,咱们有call()。不过由于兼容性的问题,不同浏览器会有不同的操作。
类数组的例子
函数的arguments对象
arguments是函数对象的内置参数。它是函数/方法在执行过程中,由传入的参数所组成的一个对象,系统内置的,可以调用。和函数声明时的参数无关(函数声明时,即使没有声明参数也不影响arguments的使用)。
arguments有两个属性:length(获取arguments对象的长度)和callee(引用当前正在执行的函数)
HTMLCollection对象
HTMLCollection 是一个接口,表示 HTML 元素的集合,它提供了可以遍历列表的方法和属性。
HTMLCollection 对象是带有方法的 HTML 元素的集合,用它可以通过元素在文档中的位置或它们的 id 属性、name 属性获取元素。在 JavaScript 中,HTMLCollection 对象的行为和只读数组一样,可以使用 JavaScript 的方括号,通过编号或名称索引一个 HTMLCollection 对象
HTMLCollection 对象是只读的,不能给它添加新元素
- document.images:[object HTMLCollection]
- document.links:[object HTMLCollection
- document.anchors:[object HTMLCollection]
- document.forms:[object HTMLCollection]
- document.scripts:[object HTMLCollection]
- document.applets:[object HTMLCollection]
- document.embeds:[object HTMLCollection]
- document.plugins:[object HTMLCollection]
- document.getElementById(‘table’).children:[object HTMLCollection]
- document.getElementById(‘table’).tBodies:[object HTMLCollection]
- document.getElementById(‘table’).rows:[object HTMLCollection]
- document.getElementById(‘row’).cells:[object HTMLCollection]
- document.getElementById(‘Map’).areas:[object HTMLCollection]
- document.all:[object HTMLAllCollection]
- document.getElementById(‘form’).elements:[object HTMLFormControlsCollection]
- document.getElementById(‘select’).options:[object HTMLOptionsCollection]
- document.getElementsByClassName(‘box’):[object HTMLCollection]
- document.getElementsByTagName(‘div’):[object HTMLCollection]
- document.getElementsByTagNameNS(‘*’, ‘a’):[object HTMLCollection]
HTMLCollection 对象的方法
- item(index) —— 返回集合中指定位置的元素(节点)
- namedItem(attrName) —— 返回集合中 name 属性或 id 属性具有指定值的元素(节点)
NodeList对象
NodeList 对象代表一个有顺序的节点列表。
我们可通过节点列表中的节点索引号来访问列表中的节点(索引号由0开始)。
节点列表可保持其自身的更新。如果节点列表或 XML 文档中的某个元素被删除或添加,列表也会被自动更新。
- document.getElementsByName(‘testbox’):[object NodeList]
- document.querySelectorAll(‘a’):[object NodeList]
- document.getElementById(‘table’).childNodes:[object NodeList]
- document.styleSheets:[object StyleSheetList]
HTMLCollection 对象和 NodeList 对象很相似,但前者可能既能用名称索引也能用数字索引。
类数组转化数组
arguments对象
arguements的数组化,只需要运用[].slice.call(),方法便可以将传递给函数的参数数组化:1
2
3
4
5function Person(){
var args=[].slice.call(arguments);
console.dir(args);//[10,20] 参数被转化成数组
}
Person(10,20);
####HTMLCollection和NodeList
对于这两个类数组对象的元素集合,如果我们使用[].slice.call()的方式,我们发现IE8及以下的浏览器会报错,报错的内容是:”Array.prototype.slice: ‘this’ 不是 JavaScript 对象”,很明显的我们发现低版本的IE浏览器的HTMLCollection和Nodelist并是不是Object的子类。所以为了让类数组转化成纯数组,我们需要进行一定的处理,借鉴几个类库的写法,我们可以:
- jQuery的早期makeArray的做法:
1 | var div=document.getElementsByTagName("div"); |
- Prototype的makeArray的做法:
1 | //这部分主流高版本的浏览器就会使用这个函数 |
参考资料
js的类数组对象HTMLCollection,NodeList,arguments
XML DOM - NodeList 对象
XML DOM HTMLCollection 对象