经实验证实js中forEach只能遍历数组,不能遍历类数组
jQuery中each方法可以遍历数组和类数组
1.forEach方法
<body>
<div>
</div>
<script>
var odiv = document.getElementsByTagName('div');//odiv是类数组
var arr = [1,2,3,4];
console.log(odiv);
console.log(arr);
arr.forEach(function(ele,index){
console.log(ele);
})
odiv.forEach(function(ele,index){
console.log(ele);
})
</script>
</body>
运行结果:
2.jQuery中each方法:
<body>
<div>
</div>
<script src="./jquery.js"></script>
<script>
var arr = [1,2,3,4];
$(arr).each(function(index,ele){
console.log(ele);
})
$('div').each(function(index,ele){
console.log(ele);
})
</script>
</body>
运行结果:
来源:https://blog.csdn.net/liuhp123/article/details/99057255