js循环中如果操作了原数组会发生什么?

767 阅读2分钟

一、背景

      今天在数据中提取数据操作了原数组,遇到一系列坑,来记录下探索记录;

二、详情

需求是这样的要对列表的三个属性操作,一个前几位标绿,两个后几位标红,然后里面是0或者null的排序剔除放到最下面,不参与排序。然后就是在剔除这一步,对原数组操作,遇到一些以前忽略的问题。

先上代码, 先排序,然后加识别属性。在html中通过solt插槽控制显示,样式放到行内未来描述展示~

let length = this.gridData.length;              this.gridData.sort((a,b)=>{                return parseInt(a.totalRank) - parseInt(b.totalRank)              });              this.gridData[0].color0 = 'blue';              this.gridData[1].color0 = 'blue';              this.gridData[2].color0 = 'blue';              this.gridData.sort((a,b)=>{                return parseInt(a.warehouseRank) - parseInt(b.warehouseRank)              });

<el-table-column           label="仓排名"          prop="warehouseRank"          :min-width="45">           <template slot-scope="props">            <div              v-if="props.row.color1 == 'red'"              style="background:#e93b64;border-radius: 50%;width: 24px;color: #fff;"            >{{props.row.warehouseRank}}</div>            <div v-else>{{props.row.warehouseRank}}</div>          </template>        </el-table-column>

  三、探索

let arr = [1,2,3,4,5,6,7,8];
let arrs = [];
for (const item of arr) {
  if (item<4) {
    let index = arr.indexOf(item);
    arr.splice(index,1)          
  }else{
    arrs.push(item)
  }
} 
console.log(arr); //[2,3,4,5,6,7,8]

想不到吧,在for of循环直接对原数组操作是不可以的,

下面换种方式

for (const item of arr) {
  if (item<4) {
    let index = arr.indexOf(item);
    arr.splice(index,1);
    console.log(arr)        
  }else{
    arrs.push(item)
  }
} //输出[4, 5, 6, 7, 8] 在这里是ok的

arr.forEach((item) => {
    if (item<4) {
    let index = arr.indexOf(item);    arr.splice(index,1);       
  }else{
    arrs.push(item)
  }
})console.log(arr) //[2, 4, 5, 6, 7, 8] 换种方式中间竟然少了个3  哦想不到 难受

//然后再像上面把arr的log放到前面判断
arr.forEach((item) => {
    if (item<4) {
    let index = arr.indexOf(item);
    arr.splice(index,1);
    console.log(arr)        
  }else{
    arrs.push(item)
  }
})
VM290:5 (7) [2, 3, 4, 5, 6, 7, 8]  
VM290:5 (6) [2, 4, 5, 6, 7, 8] //竟然输出有两个,结果又不一样了

forEach除了不支持return break 在遍历跑完回调函数后,会隐性让index自增,像这样:

arr.forEach((item, index) => {
    arr.splice(index, 1);
    console.log(1);
    //这里隐性让index自增加1 底层控制index自增for 也有
    index++;
});
 arr.filter((item) => {
    return item >= 4
});

(5) [4, 5, 6, 7, 8] //简单方便正确,如果操作原数组请用filter

总结:

  forEach删除自身元素index不会被重置,会隐性让index自增,数组也不会被删除干净

  for offorEach循环操作原数组得出返回后的原数组都不准确:其实就是会自动改变索引。

 重点!!!循环除了filter请不要操作原数组,或者深拷贝分开操作!!!

WEBGL探索之路 (二)--webgl场景构建 WEBGL探索之路 (一)--认识webgl js循环中如果操作了原数组会发生什么? 字节头条面试踩坑arguments js函数柯里化 强缓存与协商缓存属性定义集合 React Context 的理解以及应用 react shoudcomponentupdate 停止渲染 vue为什么不需要 深拷贝浅拷贝的十一种方法 import和require的区别比较 vue Vue $nextTick 深度解析 深度揭秘 Promise 微任务注册和执行过程 v8引擎如何执行一段js代码的? http3.0 2.0 1.0区别比较 宏观任务与微观任务详解