ES6 语法

123 阅读2分钟

ES6 语法

数组相关方法 :

map、filter、forEach、some、every、findIndex、reduce

一.map方法

map方法的返回值会映射到一个新数组中

let arr = [10, 20, 30, 40, 50]
                // (1)标准写法
             let res = arr.map((item, index) => {
                 console.log(item, index)
                 return item * 0.8    返回值再*0.8 到一个新数组
             })
             console.log(res)
             
             //打印为 [8, 16, 24, 32, 40]

简写

 let res = arr.map(item => item * 0.8)

map常用来渲染页面结构,万能模板:

  元素.innerHTML=数组.map(item=>``).join('')    //join('')用来去除结构中间的字符

如下列综合案列:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        .list {
            width: 990px;
            margin: 100px auto 0;
        }
        
        .item {
            padding: 15px;
            transition: all .5s;
            display: flex;
            border-top: 1px solid #e4e4e4;
        }
        
        .item:nth-child(4n) {
            margin-left: 0;
        }
        
        .item:hover {
            cursor: pointer;
            background-color: #f5f5f5;
        }
        
        .item img {
            width: 80px;
            height: 80px;
            margin-right: 10px;
        }
        
        .item .name {
            font-size: 18px;
            margin-right: 10px;
            color: #333;
            flex: 2;
        }
        
        .item .name .tag {
            display: block;
            padding: 2px;
            font-size: 12px;
            color: #999;
        }
        
        .item .price,
        .item .sub-total {
            font-size: 18px;
            color: firebrick;
            flex: 1;
        }
        
        .item .price::before,
        .item .sub-total::before,
        .amount::before {
            content: "¥";
            font-size: 12px;
        }
        
        .item .spec {
            flex: 2;
            color: #888;
            font-size: 14px;
        }
        
        .item .count {
            flex: 1;
            color: #aaa;
        }
        
        .total {
            width: 990px;
            margin: 0 auto;
            display: flex;
            justify-content: flex-end;
            border-top: 1px solid #e4e4e4;
            padding: 20px;
        }
        
        .total .amount {
            font-size: 18px;
            color: firebrick;
            font-weight: bold;
            margin-right: 50px;
        }
    </style>
</head>

<body>
    <div class="list">
        <!-- <div class="item">
      <img src="https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg" alt="">
      <p class="name">称心如意手摇咖啡磨豆机咖啡豆研磨机 <span class="tag">【赠品】10优惠券</span></p>
      <p class="spec">白色/10寸</p>
      <p class="price">289.90</p>
      <p class="count">x2</p>
      <p class="sub-total">579.80</p>
    </div> -->
    </div>
    <div class="total">
        <div>合计:<span class="amount">1000.00</span></div>
    </div>
    <script>
        const goodsList = [{
            id: '4001172',
            name: '称心如意手摇咖啡磨豆机咖啡豆研磨机',
            price: 289,
            picture: 'https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg',
            count: 2,
        }, {
            id: '4001009',
            name: '竹制干泡茶盘正方形沥水茶台品茶盘',
            price: 109,
            picture: 'https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png',
            count: 3,
        }, {
            id: '4001874',
            name: '古法温酒汝瓷酒具套装白酒杯莲花温酒器',
            price: 488,
            picture: 'https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png',
            count: 1,
        }, {
            id: '4001649',
            name: '大师监制龙泉青瓷茶叶罐',
            price: 139,
            picture: 'https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png',
            count: 1,
        }]

        //1.以前的思路:dom驱动。  遍历数组,创建dom元素,逐一添加



        //2.以后的思路:数据驱动。  遍历数组,拼接html字符串,然后替换元素的innerHTML
        //万能模板
        //元素.innerHTML=数组.map(item=>``).join('')



        //封装
        let renderData = () => {
            document.querySelector('.list').innerHTML = goodsList.map(item => `
<div class="item">
      <img src="${item.picture}" alt="">
      <p class="name">${item.name} <span class="tag">【赠品】10优惠券</span></p>
      <p class="spec">白色/10寸</p>
      <p class="price">${item.price}</p>
      <p class="count">${item.count}</p>
      <p class="sub-total">${item.price * item.count}</p>
    </div>
`).join('')
        }
        renderData()
    </script>
</body>

</html>

二.filter方法

filter常用来筛选后的新数组

filter 方法的返回值

return true:当前元素'满足'筛选条件放入到新数组

return false:当前元素'不满足'筛选条件就不会放入到新数组


        // 筛选300 以内的数
        let arr = [150, 654, 295, 332, 199, 240]
            // (1)标准写法
            // let res = arr.filter((item, index) => {
            //     console.log(item, index)
            //     if (item < 300) {
            //         return true
            //     } else {
            //         return false
            //     }
            // })
            // console.log(res)

        let res = arr.filter(item => item < 300)
        console.log(res)




        // 练习
        let personArr = [{
            name: '张三',
            age: 20
        }, {
            name: '李四',
            age: 22
        }, {
            name: '王五',
            age: 30
        }, {
            name: '张三',
            age: 14
        }]
        let kkk = personArr.filter(item => item.age > 18)
        console.log(kkk)

常与map方法一起渲染如下页面(购物车价格筛选、王者荣耀英雄筛选...) :

选择价格在100-300元之间的物品 1.jpg

选择全部

2.jpg

代码如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>商品渲染</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        .list {
            width: 990px;
            margin: 0 auto;
            display: flex;
            flex-wrap: wrap;
        }
        
        .item {
            width: 240px;
            margin-left: 10px;
            padding: 20px 30px;
            transition: all 0.5s;
            margin-bottom: 20px;
        }
        
        .item:nth-child(4n) {
            margin-left: 0;
        }
        
        .item:hover {
            box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
            transform: translate3d(0, -4px, 0);
            cursor: pointer;
        }
        
        .item img {
            width: 100%;
        }
        
        .item .name {
            font-size: 18px;
            margin-bottom: 10px;
            color: #666;
        }
        
        .item .price {
            font-size: 22px;
            color: firebrick;
        }
        
        .item .price::before {
            content: "¥";
            font-size: 14px;
        }
        
        .filter {
            display: flex;
            width: 990px;
            margin: 0 auto;
            padding: 50px 30px;
        }
        
        .filter a {
            padding: 10px 20px;
            background: #f5f5f5;
            color: #666;
            text-decoration: none;
            margin-right: 20px;
        }
        
        .filter a.active {
            background: #05943c;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="filter">
        <a href="javascript:;">0-100元</a>
        <a href="javascript:;">100-300元</a>
        <a href="javascript:;">300元以上</a>
        <a href="javascript:;" class="active">全部区间</a>
    </div>
    <div class="list">
        <!-- <div class="item">
      <img src="" alt="">
      <p class="name"></p>
      <p class="price"></p>
      </div> -->
    </div>
    <script>
        // 1. 初始化数据
        const goodsList = [{
            id: "4001172",
            name: "称心如意手摇咖啡磨豆机咖啡豆研磨机",
            price: "289.00",
            picture: "https://yanxuan-item.nosdn.127.net/84a59ff9c58a77032564e61f716846d6.jpg"
        }, {
            id: "4001594",
            name: "日式黑陶功夫茶组双侧把茶具礼盒装",
            price: "288.00",
            picture: "https://yanxuan-item.nosdn.127.net/3346b7b92f9563c7a7e24c7ead883f18.jpg"
        }, {
            id: "4001009",
            name: "竹制干泡茶盘正方形沥水茶台品茶盘",
            price: "109.00",
            picture: "https://yanxuan-item.nosdn.127.net/2d942d6bc94f1e230763e1a5a3b379e1.png"
        }, {
            id: "4001874",
            name: "古法温酒汝瓷酒具套装白酒杯莲花温酒器",
            price: "488.00",
            picture: "https://yanxuan-item.nosdn.127.net/44e51622800e4fceb6bee8e616da85fd.png"
        }, {
            id: "4001649",
            name: "大师监制龙泉青瓷茶叶罐",
            price: "139.00",
            picture: "https://yanxuan-item.nosdn.127.net/4356c9fc150753775fe56b465314f1eb.png"
        }, {
            id: "3997185",
            name: "与众不同的口感汝瓷白酒杯套组1壶4杯",
            price: "108.00",
            picture: "https://yanxuan-item.nosdn.127.net/8e21c794dfd3a4e8573273ddae50bce2.jpg"
        }, {
            id: "3997403",
            name: "手工吹制更厚实白酒杯壶套装6壶6杯",
            price: "99.00",
            picture: "https://yanxuan-item.nosdn.127.net/af2371a65f60bce152a61fc22745ff3f.jpg"
        }, {
            id: "3998274",
            name: "德国百年工艺高端水晶玻璃红酒杯2支装",
            price: "139.00",
            picture: "https://yanxuan-item.nosdn.127.net/8896b897b3ec6639bbd1134d66b9715c.jpg"
        }]


        //1.获得所有a标签
        document.querySelectorAll('.filter a ').forEach((item, index) => {
            //注册事件  给a标签注册点击事件
            item.addEventListener('click', function() {
                //(1)排他
                document.querySelector('.active').classList.remove('active')
                this.classList.add('active')
                    //(2)筛选
                if (index === 0) {
                    let res = goodsList.filter(item => item.price <= 100)
                    renderData(res)
                } else if (index === 1) {
                    let res = goodsList.filter(item => item.price > 100 && item.price <= 300)
                    renderData(res)
                } else if (index === 2) {
                    let res = goodsList.filter(item => item.price >= 300)
                    renderData(res)
                } else {
                    renderData(goodsList)
                }
            })
        })


        //封装函数
        const renderData = arr => {
                document.querySelector('.list').innerHTML = arr.map(item => `         
          <div class="item">
              <img src="${item.picture}" alt="">
              <p class="${item.name}"></p>
              <p class="${item.price}"></p>
         </div>         
          `).join('')
            }
            //渲染所有数据
        renderData(goodsList)
    </script>
</body>

</html>

三.forEach方法

原理:遍历

四.some和every方法

some作用 :判断数组中有没有元素满足条件(逻辑或)

    //2.some特点
    //2.1回调函数执行次数  !=  数组长度
    //2.2回调函数内部return
    //return true :满足条件.循环借宿,此时some自身返回值就是true
    //return false:不满足条件.循环继续,如果继续,如果遍历借宿还是false,最终some结果是false
    //2.3  some方法的返回值
    //return true  :有满足条件的元素
    //return false  :没有满足条件的元素
   案例:判断数组中有没有负数
 //全假为假
        //判断数组中有没有负数
        let arr = [50, 60, 88, -10, 30]
        let res = arr.some((item, index) => {
            if (item < 0) {
                return true
            } else {
                return false
            }
        })
        console.log(res)

        //数组中只要有负数  就返回true
        

every作用 :判断数组中有没有元素满足条件(逻辑与)

    //2.every特点
    //2.1回调函数执行次数  !=  数组长度
    //2.2回调函数内部return
    //return true :不满足条件.循环借宿,此时every自身返回值就是false
    //return false:满足条件.循环继续,如果继续,如果遍历借宿还是true,最终every结果是true
    //2.3  every方法的返回值
    //return true  :所有满足条件的元素
    //return false  :不是所有都满足条件的元素
        案例:判断数组中有没有负数
         //一假全假
        //判断数组中有没有正数
        let arr = [50, 60, 88, 10, 30]
        let res = arr.every((item, index) => {
            if (item > 0) {
                return true //如果都是正数就返回true
            } else {
                return false //有一个为负就返回true
            }
        })
        console.log(res)

四.findIndex方法

与indexof区别:

indexof() 数组元素都是'值类型' findIndex() 数组原始都引用类型

    //findIndex  特点:
    //找到 return true  返回当前下标
    //没找到  return false  循环继续,如果全部遍历完还是false  则返回值为-1

let arr = [{
                name: '张三',
                age: 20
            }, {
                name: '李四',
                age: 30
            }, {
                name: '王五',
                age: 28
            }]
            //(1)标准写法
            // let res = arr.findIndex((item, index) => {
            //     if (item.name === '王五') {
            //         return true
            //     } else {
            //         return false
            //     }
            // })
            //console.log(res)
            //(2)简写
        let res = arr.findIndex(item => item.name === '王五')
        console.log(res)

四.reduce方法

reduce () -可以用来将一个数组中的所有元素整合为一个值 -参数: 1.回调函数,通过回调函数来指定合并的规则 2.可选参数,初始值 -语法: reduce(sum,item,index) //sum一般要手动设置为0 方便后面累加计算(底层原理就是sum+=arr[i] 累加和)