前言ES5和ES6增加了很多东西。对于数组,增加了很多迭代的方法,让我们可以摒弃for循环,更方便的写JS代码。ES5和ES6中新增的数组迭代方法如下:forEachmapfiltersomeeveryreduce/reduceRightfind/findIndex其中find/findIndex是ES6新增的,其余都是ES5新增的。所以这些方法不兼容低版本的IE。下面我们就来看看这些方法是如何使用的,以及如何兼容低版本的IE。forEachforEach方法是这些方法中最基本的方法。它的作用是对数组的每个元素执行一次提供的函数。例如:vararr=[1,2,3];arr.forEach(function(element,index,array){console.log(element,index,array)})//输出10[1,2,3]21[1,2,3]32[1,2、3】forEach方法中的回调函数会依次传入三个参数:数组中当前项的值、当前项在数组中的索引、数组对象本身,forEach方法也可以pass输入第二个参数,可选。如果给forEach传递第二个参数,回调函数中的this会指向这个参数。如果不传入第二个参数,则this指向全局对象(浏览器中为window),严格模式下为undefined。vararr=[1,2,3];varobj={name:'张'};到。forEach(function(element,index,array){console.log(element,index,array,this)},obj)//output10[1,2,3]{name:"zhang"}21[1,2,3]{name:"zhang"}32[1,2,3]{name:"zhang"}下面我们用forEach写一个稍微完整一点的例子,数组求和:varsum=0;[1,2,3].forEach(function(element,index,array){console.log(array[index]==element);//truesum+=item;});控制台日志(总和);//6最后我们对低版本的IE进行扩展,这种方法兼容性比较好,代码如下:Array.prototype.forEach=Array.prototype.forEach||function(fn,context){for(vark=0,length=this.length;k=2;})console.log(newArr);//[1,2,3]console.log(newArr2);//[2,3]下面是filter方法的扩展:Array。原型.filter=Array.prototype.filter||函数(fn,上下文){vararr=[];if(typeoffn==="function"){for(vark=0,length=this.length;k=4;}varpassed=[1,2,3].some(isBigEnough);varpassed2=[1,2,3,4].some(足够大);控制台日志(通过);//falseconsole.log(passed2);//true以下是一些方法的扩展:Array.prototype.some=Array.prototype.some||函数(fn,上下文){varpassed=false;if(typeoffn==="function"){for(vark=0,length=this.length;k=3;}varpassed=[2,3,4].every(isBigEnough);varpassed2=[3,4,5].every(isBigEnough);console.log(通过);//falseconsole.log(passed2);//trueevery方法扩展如下:Array.prototype.every=Array.prototype.every||函数(fn,上下文){varpassed=true;if(typeoffn==="function"){for(vark=0,length=this.length;k-1;k-=1){this.hasOwnProperty(k)&&(previous=callback(previous,this[k],k,this));}}返回上一个;};find/findIndexfind方法用于查找参数与forEach方法相同的第一个符合条件的数组成员;所有数组成员依次执行回调函数,直到找到第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。例如:varvalue=[1,5,10,15].find(function(element,index,array){returnelement>9;});varvalue2=[1,5,10,15].find(function(element,index,array){返回元素>20;});控制台日志(值);//10console.log(value2);//undefinedfindIndex方法与find类似;但它返回数组索引中符合条件的元素的索引。如果没有成员满足条件,则返回-1。变量值=[1,5,10,15]。findIndex(function(element,index,array){返回元素>9;});变量值2=[1,5,10,15]。findIndex(function(element,index,array){返回元素>20;});控制台日志(值);//2console.log(value2);//-1对于不支持find/findIndex方法的浏览器,我们可以自己实现一个:Array.prototype.find=Array.prototype.find||function(fn,context){if(typeoffn==="function"){for(vark=0,length=this.length;k