js 优化双层循环嵌套

页面有个接口,一次性返回了5000多条数据,在数据完全加载出来之前,页面属于卡死状态,无法操作;

最开始以为是接口返回了大量数据导致的,后面发现数据才1.9M,而且axios也不存在说同步的问题;

后面发现在拿到数据后,对数据又进行了操作了;

this.formData.employeeList.forEach((item2,index2) => {
              this.insuredPersonnelList.forEach((item,index) => {
                 if (item2.employeeId ==item.employeeId) {
                       this.insurancedName.push(index);
                  }
     });

 });
两个对象都有5000多条数据,造成页面卡顿
大佬说可以先循环一次把id放到一个数组里,然后用indexOf判断;
var arr2 = [];
 this.formData.employeeList.forEach((item2, index2) => {
       arr2.push(item2.employeeId)
 });
 var arr = [];
 this.insuredPersonnelList.forEach((item, index) => {
                 arr.push(item.employeeId)
                arr.push(arr2.indexOf(item.employeeId))
                if(arr2.indexOf(item.employeeId) > -1){
                  this.insurancedName.push(index);
                }
   });

  

使用console.time(‘aa’)和console.timeEnd('aa')打印了两种方式的运行时间
 
 
计时器2是第一种方式
计时器1的时间是优化后的
第二种远优于第一种
posted @ 2020-09-17 14:42  随意滴博客  阅读(6178)  评论(0编辑  收藏  举报