遍历foreach原理

58 阅读1分钟
  1. foreach循环无法暂停,跳出需要throw Error,try catch获取
  2. foreach 原理
Array.prototype.foreach = function(fn){
   let O = this;------O 为当前调用的数组
   let len = O.length; --------先获取当前数组长度
   for(let k = 0; k < len; k++){
     if( k in O){ ------k为索引,数组也是对象,看当前索引在不在数组中
        fn(O[k], k, O);
     }
   }
}
  1. 面试题
let a = [1,2,3];
a.forEach(()=>{
   a.push(4);
})
--------只会循环3次,因为先获取了数组长度,确定循环次数
let a = [1,2,3];
a.forEach(()=>{
   a.pop();
})
--------只会循环2次,有k in O,对索引的判断