手记

js将一维数组转换为多维数组

  • 原始数据


    image.png

  • 转换后的数据


    image.png

<script type="text/javascript">
    function test() {        var arr1 = [{                id: '001',                imgPath: 'http://img1.qunarzz.com/piao/fusion/1803/95/f3dd6c383aeb3b02.png',                text: '景点门票'
            },
            {                id: '002',                imgPath: 'http://img1.qunarzz.com/piao/fusion/1804/5a/13ceb38dcf262f02.png',                text: '一日游'
            },
            {                id: '003',                imgPath: 'http://img1.qunarzz.com/piao/fusion/1804/ff/fdf170ee89594b02.png',                text: '必游榜单'
            },
            {                id: '004',                imgPath: 'http://img1.qunarzz.com/piao/fusion/1803/76/eb88861d78fb9902.png',                text: '动植物园'
            }       
        ];        console.log(arr1);        var container = [];  //定义一个数组
        arr1.forEach(function(item, index) {  //进行循环
            var num = Math.floor(index / 2);   // 向下取整,加入一个页面想展示3条数据,就将数字为几
            if (!container[num]) {
                container[num] = [];  // 如果不存在,则为null
            }
           
           container[num].push(item)  //将数据添加到数组里
        })        return container;
    }    console.log(test())    </script>// 利用此原理可制作分页



作者:jia林
链接:https://www.jianshu.com/p/d15571b7cf30


0人推荐
随时随地看视频
慕课网APP