js中伪数组如何使用数组方法

通过使用数组的原型对象加上call的特殊使用可以达到伪数组使用数组方法

    <div>1</div>
    <div>2</div>
    <div>3</div>

    <script>
        var divs=document.getElementsByTagName('div');
        //伪数组无法使用数组方法
        // divs.forEach(function (item) {
        //     console.log(item);
        // })
        //
//call的方法参考js高级第二章 可以随意控制函数中的this指向 这里指向divs
Array.prototype.forEach.call(divs,function (item,index,arr) { console.log(item,index,arr); });//foreach js6章封装的方法 </script>

 

posted @ 2019-11-25 20:49  handsomehe  阅读(1609)  评论(0编辑  收藏  举报