前言
本文章源自《JavaScript知识小册》专栏,感兴趣的话还请关注点赞收藏.
上一篇文章:《JavaScript花样百出的数组遍历》
下一篇文章:《JavaScript一文让你搞清什么是原型和原型链》
伪数组
在JavaScript中除了数组可以存储集合元素外,还有一种结构跟数组非常像,同样可以通过for循坏遍历,也拥有length属性,但并不是真正意义上的数组,这种数据结构就是伪数组,也叫类数组
代码示例
index.html代码如下
<html>
<body>
<h1>JavaScript</h1>
<div>div1</div>
<div>div2</div>
<div>div3</div>
</body>
</html>
接着在JS中获取当前div元素个数
let divs = document.getElementsByTagName('div')
console.log('divs', divs)
输出divs HTMLCollection(3) [div, div, div]
可以看到并不是Array,而是HTMLCollection,而这就是伪数组的一种体现。
详细展开来看的话,可以看到HTMLCollection跟Array一样具有length属性
一样可以for循环
for (let div of divs) {
console.log(div)
}
但是本质上并不是数组,以下会输出false
console.log(divs instanceof Array)
也不像Array可以调用push方法添加元素
divs.push('div4')
会抛出异常Uncaught TypeError: divs.push is not a function
Tips: 除了document.getElementsByTagName(),document.getElementsByClassName()也是返回HTMLCollection[],还有一个类似的document.querySelectorAll(),只不过它返回的则是NodeList[],但两者本质上都不是Array
额外补充一点,其实Function中的arguments也是伪数组
function print() {
console.log(arguments instanceof Array) // 输出false
}
print(1,'123',true)
转换为数组
Array.slice()
伪数组可以通过调用Array的slice方法,从而将其转换为一个真正的Array
let divs = document.getElementsByTagName('div')
console.log('divs', divs) // HTMLCollection
divs = Array.prototype.slice(divs) // 转换
console.log(divs instanceof Array) // 输出true,这时dvis变成了真正的数组,也可以调用push()等方法
Array.from()
也可以调用Array的from方法,将伪数组转换为真正的数组
let divs = document.getElementsByTagName('div')
let arr = Array.from(arrayLike)
console.log(arr instanceof Array)
自定义伪数组
伪数组是可以自定义的,和前面的HTMLCollection等差不多
// 自定义伪数组
let sourceList = {
0: 'English',
1: 'Java',
2: 'Spring',
length: 3
}
conso.log()