标签:sharp console element from call foreach rom opera pre
对DOM元素进行map、forEach操作时候需要进行遍历,伪数组遍历会报错:‘elem.map is not a function‘,为了避免这个问题,需要进行转换。
Array.prototype.slice.call(元素对象)
let elem1 = Array.prototype.slice.call(elem)
Array.from(元素对象)
let elem2 = Array.from(elem)
<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>
标签:sharp console element from call foreach rom opera pre
原文地址:https://www.cnblogs.com/li923/p/11724038.html