class array to object

During the interview, you need to convert the array-like object into an array and record the method.
Often when operating dom, what is obtained is an array-like object, so the method of the array cannot be directly used.

  1. ES6 syntax Array.from()
let arr=Array.from(list);
  1. Use the method Array.prototype.slice.call on the prototype chain
let p=document.getElementsByTagName('p');
    p.forEach(item=>{
    
    
        item.addEventListener('click',()=>{
    
    
            console.log(item.innerHtml)
        })
    })

insert image description here
Traversing with a class array is an error, so it needs to be converted to a real array

 let p=document.getElementsByTagName('p');
    p=Array.prototype.slice.call(p);
    p.forEach(item=>{
    
    
        item.addEventListener('click',()=>{
    
    
            console.log(item)
        })
    })

3. Use the […] deconstruction method to convert it into an array

let p=document.getElementsByTagName('p');
    p=[...p]
    p.forEach(item=>{
    
    
        item.addEventListener('click',()=>{
    
    
            console.log(item)
        })
    })```

 

Guess you like

Origin blog.csdn.net/weixiwo/article/details/129480642
Recommended