js数组方法 • 下篇

226 阅读3分钟

1.every方法

  • 检测数组中的元素是否全部满足条件
//应用场景:购物车全选功能
  computed: {
     isAll: {
       set(val){
         //点击全选,小选全部勾上
         this.arr.forEach(item =>item.c = val );
       },
           
      //forEach方法循环   
       get(){
          let flag = true;
          this.arr.forEach((item) => {
            if (!item.c) {
             flag = false;
            }
          });
          return flag;
   
         //every循环方法  返回一个布尔值,全部为true返回true,否则返回false
         return this.arr.every(item=>item.c)
       }
     },
   },

2. filter方法

  • 过滤原数组,返回新数组
  del(id) {
      //filter方法循环删除元素
       this.list = this.list.filter(item => item.id !== id);
     },
         
     //forEach方法循环删除元素    
     del(id) {
       this.list.forEach((item, index, arr) => {
         if (item.id === id) {
           // 数组splice方法删除元素
           this.list.splice(index, 1);
         }
       });
     },
         
         
      if (this.isSel === 'yes') {
         // filter 数组筛选/过滤  
         // 返回一个新数组, 会将循环过程中符合条件的加入新数组最后返回
          return this.list.filter(item => item.isDone)
          
          //forEach方法筛选   
         let newArr = []
         // 如果当前是 yes 就把 isDone 为 true 的数据放到新数组中返回
         this.list.forEach(item => {
             if (item.isDone) {
                 newArr.push(item)
           }
         })
         return newArr
       }

3.findIndex方法

  // 根据 id 找到对应的数据并删除
     //forEach方法循环删除元素
        this.list.forEach((item, index) => {
          if (item.id === id) {
            this.list.splice(index, 1)
          }
       })
 ​
       // 根据自定义的条件查找索引: findIndex
       // 调用这个方法也会循环数组, 有一个返回值是索引
       const index = this.list.findIndex(item => item.id === id)
       this.list.splice(index, 1)
     },

4.forEach 按升序依次遍历数组中的值

  • 语法 arr.forEach(function(value, index, arr), this);

  • value(必须): 当前遍历时的数组值。

    index(可选): 当前遍历时的索引值。

    arr(可选): 数组对象本身。

    this(可选): 执行回调函数时的。

   let arr = [ 1,2,3,4,5,6]
         arr.forEach((value,index)=>{
             console.log(value)//值
             console.log(index)//下标
 ​

5.some()检测数组中是否存在满足条件的元素

  • 语法 arr.some(function(value, index, arr), this);

    参数值同froEach一样

    返回值:布尔类型 ture / false

//只要有满足条件的就返回true
 let arr = [1,2,3,4,5]
         let result = arr.some(value=>value>6)//false
         let result1 = arr.some(value=>value>2)//true
         console.log(result,result1)
 ​

6.map() 对数组中的每一个元素都进行处理,返回新的数组

 let arr = [1,2,3,4,5]
         let result = arr.map(item=> item*2)
         console.log(result)//[2, 4, 6, 8, 10]
 ​

7..keys() 遍历键名 / values() 遍历键值/ entries() 遍历键值对

  for(let i of ['a','b','c'].keys()){
             console.log(i)//keys()遍历下标 0 1 2
         }
         for(let item of ['a','b','c'].values()){
             console.log(item)//values()遍历值 a b c
         }
         for (let [i,item] of ['a','b','c'].entries()){
             console.log(i,item)//entries()遍历下标以及内容 
         }
 ​

8.reduce()数组的累加器,合并成为一个值。

  • 语法 arr.reduce((total, value, index, arr), init)

    参数 total(必须):初始值,之后为上一次回调的返回值。

    value(必须): 数组元素的值。

    index(可选): 索引值。

    arr(可选): 数组对象。

    init(可选): 初始值。

    返回值 :累加后的值

    //最后一个参数0用来兜底
     let arr = [1,2,3,4,5]
             let sum = arr.reduce((total,value)=>total +value,0)
             console.log(sum)//15
     ​
      //计算购物车总数量
      ////先用filter 把选中的过滤出来,再用reduce累加数量,要返回
           return this.list.filter((item) => item.goods_state)
           .reduce((sum, item) => (sum += item.goods_count * item.goods_price), 0)
    

9.flat()深度遍历展开数组

  • 参数: depth(可选): 提取嵌套数组的结构深度,默认为1。

    返回值:展开后的新数组。

    flat方法会移除数组中的空白项

    若不清楚有多少层嵌套,可以直接用 Infinity 设置,就可全部展开

    Infinity 正无穷大的数值。

       let arr = [1,2,[3,[4,[5]]],6]
             let one = arr.flat()
             console.log(one)//[1, 2, 3, Array(2), 6]
      
             let inf = arr.flat(Infinity)
             console.log(inf)//[1, 2, 3, 4, 5, 6]
     ​
    

10.find()

findfindIndex的唯一区别在于,它返回的是实际值,而不是索引。实际工作中,咱们可以重用已经实现的findIndex

 [1, 2, 3, 4, 5, 6, 7].find(value => value === 5); // 5

11.填充数组长度

 //表格占位长度
    let length = Number(res.data.groups.batterySize);
    const obj = {};
    let tableData = new Array(length).fill(obj);
       this.tableData = tableData.map((item, index) => ({
            batId: index + 1,
            batteryNo: "",
            batteryName: "",
            id: null,
            status:null,
            number: index + 1,
          }));
          //返回的数据有绑定的电池替换填充的数据
          this.tableData.forEach((item) => {
            res.data.groups.batteryList.forEach((item1) => {
              if (item.number == item1.number) {
                that.tableData[item.number - 1] = item1;
              }
            });
          });

12.数组去重

//定义去重函数---使用Map  引用类型去重-根据属性名筛选Key
 arrayToHeavy(arr,key) {
      const result = [];
      const mapList = new Map();
      arr.forEach((item) => {
        if (!mapList.has(item.key)) {
          result.push(item);
          mapList.set(item.key, true);
        }
      });
      return result;
    },
 //数组去重
this.newArr = this.arrayToHeavy(this.arr,"url");