前言
本文章源自《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()