js分享19-数组扁平化&图片懒加载(小白必看)

42 阅读1分钟

数组扁平化

  • 数组的扁平化就是将一个嵌套多层的数组转换为只有一层的数组
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
    // 方法一:
        const data = [undefined,{ name: 'QF001' }, function () { console.log(123) },null,true,false,1,2,3,[4,5,6,[7,8,9,[10,11,12]]]]
        /**
         *  当前方法如果不传参, 那么会帮我们执行 一层 扁平化
         * 
         *  Infinity 在 JS 中表示一个 无穷大的 数字
        */
        const newData = data.flat(Infinity)
        console.log(newData)

    // 方法二:
        /**
         *  undefined 和 null 不能出现在数组中
         *  当前写法会将数组中 所有的元素转成字符串
         * 
         * 
         *  注意: 将来我们只会遇到 纯字符串数组 或者 纯对象数组
         * 
         * 
         *      所以当前方法将来只适用于 纯字符串组成的数组
        */
        const newData = data.toString().split(',')
        console.log(newData)
        
    // 方法三:
        function flat(arr) {
            // 1. 创建一个数组, 存储扁平化后的内容
            const target = []
            // 2. 核心代码: 完成扁平化
            function setArr(origin) {
                origin.forEach(item => {
                    if (Object.prototype.toString.call(item) !== '[object Array]') {
                        target.push(item)
                    } else {
                        // 当前分支只要执行, item 的值 一定是一个数组
                        setArr(item)
                    }
                })
            }
            setArr(arr)
            // 3. 将处理好的数据返回
            return target
        }
        const res = flat(data)
        console.log(res)
    </script>
</body>

</html>

图片懒加载

  • 在 图片 展示出来前, 我们不渲染图片等到图片到达(快到达) 可视区域窗口的时候, 我们再渲染图片
  • 懒加载的优点: 提升首页加载速度
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .top {
            height: 2000px;
        }

        img {
            width: 500px;
            height: 500px;
        }
    </style>
</head>
<body>
    <div class="top"></div>
    <img data-src="https://img1.baidu.com/it/u=481689849,3217240113&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="">
    <script>
        const imgEl = document.querySelector('img')
        window.onscroll = function () {
            // console.log('开始判断')
            if (imgEl.src !== '') return
            // 屏幕的高度 + 页面卷去的高度 > 图片的顶部偏移量
            const h = window.innerHeight
            const pageH = document.documentElement.scrollTop
            const top = imgEl.offsetTop
            // - 200 是为了留出一点让网络请求图片的时间, 其实当前案例中 加不加 无所谓
            if (h + pageH > top - 200) {
                console.log('渲染图片')
                imgEl.src = imgEl.dataset.src
            }
        }
    </script>
</body>
</html>