大飞_dafei

导航

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

 

posted on 2020-06-14 17:03  大飞_dafei  阅读(5752)  评论(0编辑  收藏  举报