原生JS中forEach只能遍历数组,不能遍历类数组

痞子三分冷 提交于 2019-11-26 19:24:40

经实验证实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>

运行结果:

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!