当前位置: 首页 > Web前端 > JavaScript

JavaScript中forEach方法的原理与应用

时间:2023-03-27 18:03:29 JavaScript

JavaScript中forEach方法的原理与应用上一篇文章比较了for循环与js中forEach方法的区别。今天手写一些forEach方法,方便更深入的理解。先看MDN中forEach方法的语法arr.forEach(callback(currentValue[,index[,array]])[,thisArg])也就是说forEach方法传入一个回调函数,第一个参数其中是当前值,第二个索引,第三个是当前数组,还有一个额外的可选对象,用于指定回调方法的this首先,我们测试一下forEach方法constarr2=['apply','call','bind']leta=arr2.forEach((item,index)=>{console.log(item)})console.log(a)//undefinedconstarr2=['apply','call','bind']varparams={data:1}arr2.forEach(function(item,index){console.log(this)console.log('data',this.data)},{data:2})arr2.forEach((item,index)=>{console.log(this)console.log('data',this.data)},{data:2})强烈建议打印上面控制台输出,我们可以看到实现时需要注意的一些事情1.如果使用箭头函数表达式来pass在函数参数中,thisArg参数将被忽略,因为箭头函数在词法上绑定到this值。2、使用普通函数时,第二个参数会作为对应的this指向。3、forEach只是执行回调函数,没有返回值。然后我们可以简单地实现Array.prototype.MyForEach=function(callback,thisArg){for(leti=0;i