伪数组转为真数组
伪数组转为真数组
对DOM元素进行map、forEach操作时候需要进行遍历,伪数组遍历会报错:'elem.map is not a function',为了避免这个问题,需要进行转换。
(1) ES5 转为真数组
Array.prototype.slice.call(元素对象)
let elem1 = Array.prototype.slice.call(elem)
(2) ES6 转为真数组
Array.from(元素对象)
let elem2 = Array.from(elem)
(3) 例子
<ul> <li class="a" ></li> <li class="a" ></li> <li class="a" ></li> <li class="a" ></li> <li class="a" ></li> </ul> <script> /* 获取li元素*/ let elem = document.getElementsByClassName('a') /* 这样写是错误的,因为是伪数组*/ elem.map((item,index,elem) => { console.log(item +'---'+index + '----'+elem) /*elem.map is not a function*/ }) // (1)es6 转为真数组 let elem1 = Array.from(elem) // (2)es5 转为真数组 let elem2 = Array.prototype.slice.call(elem) console.log(elem) console.log(typeof elem) console.log(elem1) console.log(elem2) elem1.map((item,index,elem1) => { console.log(item +'---'+index + '----'+elem1) }) elem2.map((item,index,elem2) => { console.log(item +'---'+index + '----'+elem2) }) </script>