数组迭代方法使用

122 阅读1分钟

数组迭代方法

01-数组map方法

 <script>
       
       /* 
       1.数组map方法作用:  映射数组
         说人话:按照某种映射关系, 把数组的每一个元素给修改了
         举例:全场8折:  数组的每一个元素 * 0.8

       2. map方法特点
        2.1  回调函数执行次数  ==    数组长度
        2.2  回调函数内部的return
            * return 新数组的元素
            * 如果没有return, 则map的返回值都是undefined
        2.3  map方法的返回值
            * 返回映射之后的新数组
       */

       let arr = [ 88,90,100,20,50 ]
        //完整写法
       let res =  arr.map( (item,index) => {
           return item*0.8
       } )
       //箭头函数如果形参只有一个可以省略小括号, 如果函数体只有一行可以省略大括号(必须省略return)
       let res1 =  arr.map( item=>item*0.8 )
       console.log( res )
       
       
    </script>

02-数组filter方法

 <script>
       
       /* 
       1.数组filter方法作用:  筛选数组
         * 应用场景: 筛选数组,将符合条件的元素放入新数组中
         * 举例: 找出数组中所有大于10的元素

       2. filter方法特点
        2.1  回调函数执行次数  ==    数组长度
        2.2  回调函数内部的return
            * return true : 符合筛选条件,放入新数组中
            * return false : 不符合筛选条件,不放入新数组中
        2.3  filter方法的返回值
            * 返回筛选之后的新数组
       */

       let arr = [ 88,90,100,20,50 ]
       //需求:找出50以上的元素
        //完整写法
    //    let res = arr.filter( (item,index)=>{
    //         if( item >= 50 ){
    //             return true
    //         }else{
    //             return false
    //         }
    //    })

    let res = arr.filter(item=>item >= 50)
    console.log( res )
    </script>

03-数组forEach

    /* 
       1.数组forEach方法作用:  遍历数组
         * 应用场景:  和 for(let i=0;i<arr.length;i++){} 功能一致

       2. forEach方法特点
        2.1  回调函数执行次数  ==    数组长度
        2.2  回调函数内部的return
            * 没有返回值
        2.3  forEach方法的返回值
            * 没有返回值
       */  

       let arr = [45,60,88,90,20]

       arr.forEach((item,index)=>{
           console.log(item,index)
       })
       

04-数组some方法

    <script>
        /* 
       1.数组some方法作用:   判断数组中是否有符合条件的元素
         * 应用场景:  非空判断(判断多个表单元素,有没有空文本)
         * 举例 : 判断数组中有没有负数

       2. some方法特点
        2.1  回调函数执行次数  !=  数组长度
        2.2  回调函数内部的return
            * return true : 循环结束。 找到了满足条件的元素
            * return false : 循环继续。 没找到,循环继续。 如果所有元素全部遍历还是没找到,最终结果就是false
        2.3  some方法的返回值
            * true : 有符合条件的元素
            * false : 没有符合条件的元素
       */     

        let arr = [10,20,50,60,70,80]
       //标准写法
    //    let res = arr.some((item,index)=>{
    //        if( item < 0 ){
    //            return true
    //        }else{
    //            return false
    //        }
    //    })
        
        //简写
       let res = arr.some(item=>item < 0)
       console.log( res )
       
    </script>

05-数组every方法

  <script>
        /* 
       1.数组every方法作用:   判断数组中 是否所有的 元素都满足条件
         * 应用场景:  开关思想 (购物车全选框)
         * 举例 : 判断数组中是不是都是正数

       2. every方法特点
        2.1  回调函数执行次数  !=  数组长度
        2.2  回调函数内部的return
            * return true : 循环继续, 满足条件,如果所有的元素全部遍历还是true,则最终的结果就是true
            * return false : 循环结束。 只要要到不满足条件的元素,循环结束。最终的结果false
        2.3  every方法的返回值
            * true : 所有的元素 都符合条件
            * false : 有元素 不符合条件
       */     

        let arr = [10,20,50,60,70,80]
       //标准写法
       let res = arr.every((item,index)=>{
           if( item >= 0 ){
               return true
           }else{
               return false
           }
       })
       console.log(res)
       
    </script>

06-数组findIndex方法

<script>
        /* 
       1.数组findIndex方法作用:   查找元素的下标
         * 数组的findIndex与indexOf异同点
            相同点:功能一致,都是查找元素下标。 有则返回下标,无则返回固定值-1
            不同点:应用场景不同
                indexOf : 查找数组中的元素都是值类型
                findIndex : 查找数组中的元素都是引用类型

       2. findIndex方法特点
        2.1  回调函数执行次数  !=  数组长度
        2.2  回调函数内部的return
            * return true : 循环结束。 找到了,此时返回值就是下标
            * return false : 循环继续。 没找到,循环继续。 如果所有元素全部遍历还是没找到,最终结果就是-1
        2.3  some方法的返回值
            * 元素下标 或者 -1
       */   
      
       let arr = [
           {name:'张三',age:20},
           {name:'李四',age:18},
           {name:'王五',age:16},
       ]

       //需求:找名字为王五的人在哪里
    //    let res = arr.findIndex(item=>{
    //        if( item.name == 'sfs' ){
    //            return true
    //        }else{
    //            return false
    //        }
    //    })

      let res = arr.findIndex(item=>item.name == '王五')
      console.log(res)
      
    </script>

07-数组reduce方法

 <script>
        /* 1.数组reduce方法 :  数组累加器方法
            * 对数组每一个元素执行一次回调函数,累加最后一次回调的结果 
        2.reduce场景: 数组元素求和、求数组元素最大值
        
        */ 
       
        let arr = [20,55,60]

        // let sum = 0
        // for(let i = 0;i<arr.length;i++){
        //     sum = sum + arr[i]
        // }
        // console.log( sum )
        

        /* 
        第一个参数:回调   (上一次值,当前值,当前下标)=>{}
            * 默认下标不是从0开始,而是从1开始。 开发中一般需要设置默认值
            * return 值 就是下一次 sum的值
        第二个参数: 初始值
            * 一般需要设置初始值为0, 如果不设置遇到空数组则会报错
        reduce方法返回值是 : 最后一次sum的结果
        */
    //    let res = arr.reduce( ( sum,item,index )=>{
    //         console.log( sum,item,index)
    //         return sum + item
            
    //     } , 0 )

        let res = arr.reduce( ( sum,item )=>sum + item , 0 )

        console.log( res )
        
    </script>

some场景

01-购物车列表展示

<!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元素,逐一添加
    // for(let i = 0;i<goodsList.length;i++){
    //   //(1)创建空标签
    //   let div = document.createElement('div')
    //   //(2)设置内容
    //   div.innerHTML = `<div class="item">
    //   <img src="${goodsList[i].picture}" alt="">
    //   <p class="name">${goodsList[i].name} <span class="tag">【赠品】10优惠券</span></p>
    //   <p class="price">${goodsList[i].price}</p>
    //   <p class="count">x${goodsList[i].count}</p>
    //   <p class="sub-total">${goodsList[i].price * goodsList[i].count}</p>
    //   </div>`
    //   //(3)添加到页面
    //   document.querySelector('.list').appendChild(div)
    // }


    //2.以后的思路:数据驱动。  遍历数组,拼接html字符串,然后替换元素的innerHTML

    //(1) map : 把数组中的数据 映射成  对应的html字符串
    // let res = goodsList.map(item=>{
    //   return `<div class="item">
    //   <img src="${item.picture}" alt="">
    //   <p class="name">${item.name} <span class="tag">【赠品】10优惠券</span></p>
    //   <p class="price">${item.price}</p>
    //   <p class="count">x${item.count}</p>
    //   <p class="sub-total">${item.price * item.count}</p>
    //   </div>`
    // })
    // console.log( res )
    // //(2)拼接字符串
    // let htmlStr = res.join('')
    // console.log( htmlStr )
    // //(3)替换元素的innerHTML
    // document.querySelector('.list').innerHTML = htmlStr

    document.querySelector('.list').innerHTML =  goodsList.map(item=>{
      return `<div class="item">
      <img src="${item.picture}" alt="">
      <p class="name">${item.name} <span class="tag">【赠品】10优惠券</span></p>
      <p class="price">${item.price}</p>
      <p class="count">x${item.count}</p>
      <p class="sub-total">${item.price * item.count}</p>
      </div>`
    }).join('')

    //求所有商品总价格
    document.querySelector('.amount').innerText =  goodsList.reduce((sum,item)=>sum+item.price*item.count,0)
  </script>
</body>
</html>

02-购物车价格筛选

<!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标签
      let aList = document.querySelectorAll(".filter>a")
      //2.注册事件
      for (let i = 0; i < aList.length; i++) {
        aList[i].onclick = function() {
          //3.排他
          //(1)类选择器 干掉兄弟
          document.querySelector("a.active").classList.remove("active")
          //(2)复活自己
          this.classList.add("active")
          //筛选
          if (i == 0) {// 0 - 100
            renderData( goodsList.filter(item => item.price < 100) ) 
          } else if (i == 1) {
            //100-300
            renderData( goodsList.filter(item => item.price >= 100 && item.price < 300) ) 
          } else if( i == 2){
            renderData( goodsList.filter(item => item.price >= 300) ) 
          }else{
            renderData( goodsList ) 
          }
        }
      }

      const renderData = arr => {
        document.querySelector(".list").innerHTML = arr.map(item => `<div class="item">
        <img src="${item.picture}" alt="">
        <p class="name">${item.name}</p>
        <p class="price">${item.price}</p>
        </div>`).join("")
      }

      //页面一加载,默认渲染所有数据
      renderData( goodsList )
    </script>
  </body>
</html>

03-every 全选框

<!DOCTYPE html>
<html>

<head lang="en">
  <meta charset="UTF-8" />
  <title></title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    table {
      border-collapse: collapse;
      border: 1px solid #c0c0c0;
      width: 500px;
      margin: 100px auto;
      text-align: center;
    }

    th {
      background-color: #09c;
      font: bold 16px '微软雅黑';
      color: #fff;
      height: 24px;
    }

    td {
      border: 1px solid #d0d0d0;
      color: #404060;
      padding: 10px;
    }
  </style>
</head>

<body>
  <table>
    <tr>
      <th><input type="checkbox" id="checkAll" />全选/全不选</th>
      <th>菜名</th>
      <th>商家</th>
      <th>价格</th>
    </tr>
    <tr>
      <td>
        <input type="checkbox" class="check" />
      </td>
      <td>红烧肉</td>
      <td>隆江猪脚饭</td>
      <td>¥200</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" class="check" />
      </td>
      <td>香酥排骨</td>
      <td>隆江猪脚饭</td>
      <td>¥998</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" class="check" />
      </td>
      <td>北京烤鸭</td>
      <td>隆江猪脚饭</td>
      <td>¥88</td>
    </tr>
  </table>

  <script>
    /* 思路分析
    1. 点击全选按钮 : 设置每一个选择框checked值与自身一致
      自己是true:每一个选择框也是true. 否则就是false
    
    2.点击下方每一个选择框 :  判断是否所有选择框都选中
      true  : 都选中, 修改全选框checked值为true.
      false : 没有都选中, 修改全选框checked值为false.
    */

    //1.获取元素
    let checkAll = document.querySelector('#checkAll')
    let checkList = document.querySelectorAll('.check')

    //2.注册事件

    //2.1 全选框
    checkAll.onclick = function () {
      //3.设置每一个选择框checked值与自身checked一致   
      console.log(this)//自己   (环境对象)
      for (let i = 0; i < checkList.length; i++) {
        checkList[i].checked = this.checked
      }
    }

    //2.2 点击每一个选择框 : 判断数组中是否所有选择框checked值都为true
    /* 
    开关思想 :  判断数组中是否所有的元素都满足条件
    1.声明开关变量 :  let flag = true
    2.检测开关变量 :  遍历数组,找false
    3.获取开关结果
     */
    for(let i = 0;i<checkList.length;i++){
      checkList[i].onclick = function(){
        //3. 事件处理
        //判断 checkList是否所有的元素checked值都是true
        checkAll.checked = Array.from(checkList).every(item=>item.checked)
      }
    }
  </script>
</body>

</html>