js 遍歷對象forEach is not a function [DOM集合--類數組對象轉化為數組 ]


js 遍歷對象forEach is not a function [DOM集合--類數組對象轉化為數組 ]

分析: 出現這種錯誤原因:

原生js 獲取的DOM集合是一個類數組對象,所以不能直接利用[ forEach,map ]遍歷,需要進行轉換為數組后,才能用數組方法遍歷

錯誤再現:

// 這樣會報錯
let metaArr = document.getElementsByTagName('meta');
metaArr.forEach((item,index)=>{
    console.log(item);
});

 

 

01) 解決方法01

let metaArr = document.getElementsByTagName('meta');
Array.prototype.forEach.call(metaArr,function (item,index) {
    console.log(item);
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM