伪数组怎么转为真正的数组呢~

在用js获取元素对象的时候,很多时候需要进行将伪数组转为真正的数组的,那么如何用呢~~~

废话少说,直接上代码~

<!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>

 

posted @ 2017-12-15 15:42  Mrspao  阅读(890)  评论(0编辑  收藏  举报