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); });