**数组:**可以调用数组自身的方法。proto__处的值为Array
伪数组:具备数组的一些属性,但是不能调用数组自身的方法(虽然不能调用自身的方法,但是我们可以把伪数组赋值给一个变量,通过变量调用伪数组自身的方法)。__proto__处的值不是Array。
我们先设置两个查找元素的方法然后输出:
我们可以看到通过querySelectorAll和getElementsByClassName查找到的返回值分别是NodeList 和 HTMLCollection。这两个都是一个伪数组。但是他们在__proto__处的值不一样。
NodeList 和 HTMLCollection的区别:
1.NodeList伪数组点击开__proto__的时候,发现里面有forEach方法。
2.HTMLCollection伪数组点击开__proto,里面没有forEach方法。
所以NodeList这类伪数组也可以通过forEach遍历
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.father {
width: 300px;
height: 100px;
background-color: pink;
position: relative;
margin: 20px;
}
.son {
width: 30px;
line-height: 30px;
background-color: skyblue;
text-align: center;
position: absolute;
right: -30px;
top: 0;
cursor: pointer;
}
</style>
</head>
<body>
<!-- 父盒子是广告分区, son 是关闭按钮 -->
<div class="father">
父级广告1
<div class="son">
x
</div>
</div>
<div class="father">
父级广告2
<div class="son">
x
</div>
</div>
<div class="father">
父级广告3
<div class="son">
x
</div>
</div>
<div class="father">
父级广告4
<div class="son">
x
</div>
</div>
<script>
// 1. 查找元素
var sons = document.querySelectorAll('.son');
var sons2 = document.getElementsByClassName('son');
console.log(sons); // NodeList
console.log(sons2); // HTMLCollection
//forEach 遍历每个子元素
sons.forEach(function (item, index) {
console.log(item);
});
</script>
</body>
</html>
输出的结果:
我们通过NodeList 和 HTMLCollection发现我们在通过querySelector获取元素的时候可以使用forEach的方法进行遍历输出。