javascript中的伪数组
欢迎访问我的博客,祝码农同胞们早日走上人生巅峰,迎娶白富美~~~
什么是伪数组
假如有这样一段代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
去看控制台看看
上图就是一个伪数组,长相很像数组,但是将他的原型_proto_
打开看看,它没有数组的splice
,concat
,pop
等方法
特点:
- 具有
length
属性 - 按索引方式存储数组
- 不具有数组的方法
将伪数组转化为真数组
可以通过
call
或者apply
的方法,将伪数组转化为真数组
1 2 | Array.prototype.slice.call(liArr.children) // Array.prototype.slice.apply(liArr.children) |
原理
借用数组原型方法:
1 2 3 4 5 6 7 8 9 10 11 12 | var arr = Array.prototype.slice.call(liArr.children); Array.prototype.forEach.call(liArr.children, function(v) { // 循环liArr.children对象 }); // push // some // every // filter // map // ... |
可以简化为:
1 2 | Array.prototype.slice.call(liArr.children) // 此时已经改变了 this 指向,使得 liArr.children 拥有了真数组的原型方法 |
总结
- 伪数组没有数组
Array.prototype
的属性值,类型是Object
,而数组类型是Array
- 数组是基于索引的实现, length 会自动更新,而对象是键值对
- 使用对象可以创建伪数组,伪数组可以利用
call
或者apply
很方便的转化为真数组