JavaScript中for循环和forEach的区别这么多!在我们平时的工作中,我们有几种循环遍历数组的方法,但是最常用的应该是for循环和使用数组的forEach方法。今天就来全面比较一下两者的区别吧,请大家看好。首先我们定义两个数组constarr1=['apply','call','bind']constarr2=['apply','call','bind']接下来使用不同的遍历方式运行不同的代码块,做一个比较1.执行普通代码for(leti=0;i{console.log(item)})打印相同的结果2.修改代码中的原始数组for(leti=0;i{item=item+1})console.log(arr2)arr1改变,arr2不改变3.使用异步函数console.log(newDate())for(leti=0;i{console.log(arr1[i])console.log(newDate())},3000)}//arr2.forEach((item,index)=>{//setTimeout(()=>{//console.log(item)//console.log(newDate())//},3000)//})console.log(newDate())先打印第一个控制台,再打印最后一个控制台,最后执行中间四个。代码使用awaitfunctiontest(){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve(newDate())},3000)})}asyncfunctionfn(){for(leti=0;i{console.log(awaittest())})同时打印出来5.代码中包含breakfunctiontest(){for(leti=0;i{console.log(item)//if(index===1){//break//}})}test()test2()不注释掉会报错六、代码中包含returnfunctiontest(){for(leti=0;i{console.log(item)if(index===1){return}})}test()test2()执行test函数时,return终止test2函数的执行。test2函数执行时,遇到return,没有终止。总结:1.处理原来使用数组时使用for循环2.forEach中不能使用break,不支持return。3.for循环可以实现区间打印,也就是说forEach不支持异步到同步的本质区别:前者是遍历,后者其实是迭代遍历:指的是每个成员定期、一次性的访问.迭代:迭代是递归的一种特殊形式。它是迭代器提供的一种方法。默认情况下,它按照一定的顺序一个一个地访问数据结构成员。特别提醒forEach回调函数的数组参数的操作,原来的数组变了vararray=[1,2,3];array.forEach(function(value,index,data){++value;data.push(value);});console.log(array,"array");//[1,2,3,2,3,4]"array"然后我们来实现forEach方法明天告诉你看看迭代器是什么