js 遍历对象forEach is not a function [DOM集合--类数组对象转化为数组 ]

分析: 出现这种错误原因:

原生js 获取的DOM集合是一个类数组对象,所以不能直接利用[ forEach,map ]遍历,需要进行转换为数组后,才能用数组方法遍历

错误再现:

// 这样会报错
let metaArr = document.getElementsByTagName('meta');
metaArr.forEach((item,index)=>{
    console.log(item);
});

js 遍历对象forEach is not a function [DOM集合--类数组对象转化为数组 ]

 

 

01) 解决方法01

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

 

相关文章:

  • 2021-07-11
  • 2021-12-19
  • 2021-08-02
  • 2021-09-30
  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案