在用js獲取元素對象的時候,不少時候須要進行將僞數組轉爲真正的數組的,那麼如何用呢~~~javascript
廢話少說,直接上代碼~css
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <title>test overflow</title> <style type="text/css"> /* 滾動的三要素: 1:父盒子設置width爲100%,橫向滾動overflow-x: scroll,不換行white-space: nowrap; 2.子元素設置爲行內塊級元素display: inline-block; */ * { margin: 0; padding: 0; } ul { width: 100%; padding: 20px; border: 1px solid red; overflow-x: auto; white-space: nowrap; } li { display: inline-block; border: 1px solid yellow; padding: 10px 30px; } </style> </head> <body> <ul> <li class="flex" >美妝</li> <li class="flex" >服飾</li> <li class="flex" >衣服</li> <li class="flex" >化妝品</li> <li class="flex" >童裝</li> </ul> </body> <script type="text/javascript"> /* 僞數組轉爲真數組 (1)Array.from(元素對象) (2)Array.prototype.slice.call(元素對象) */ let // 獲取li元素 oLi = document.getElementsByClassName('flex') // (1)es6 轉爲真數組 aLi1 = Array.from(oLi) // (2)es5 轉爲真數組 aLi2 = Array.prototype.slice.call(oLi) console.log(oLi) console.log(typeof oLi) console.log(aLi1) console.log(aLi2) aLi1.map((item,index,oli) => { console.log(item +'---------------'+index + '------------'+oli) }) // 報錯 oLi.map((item,index,oli) => { console.log(item +'---------------'+index + '------------'+oli) }) </script> </html>