原生js获取dom数组对象后无法使用forEach 方法
例如:
document.getElementsByClassName('xx').forEach(item=>{})
在调试工具和直接调用的时候不会有问题,但是如果通过webpack打包后就会报 Uncaught TypeError: forEach is not a function 错误
原因:原生js获取的DOM集合是一个类数组对象,所以不能直接利用数组的方法(例如:forEach,map等),需要进行转换为数组后,才能用数组的方法!
解决方案:
1. 使用jquery
2. 转换为数组:
let list = document.getElementsByClassName('xx')
list = [...list]
list.forEach(xxx)
3. 通过Array.from()转换为数组
let list = Array.from(document.getElementsByClassName('xx'))
list.forEach(xxx)
0 评论