原生JS中forEach 和JQ中each方法

經實驗證實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>

運行結果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章