ES5新增了写数组的方法:
forEach、map、filter、some、every、indexOf、lastIndexOf、reduce、reduceRight
浏览器支持情况: Opera 11+、firfox 3.6+、safari 5+、chrome 8+、internet explorer 9+
浏览器支持情况: Opera 11+、firfox 3.6+、safari 5+、chrome 8+、internet explorer 9+
forEach
forEach
:遍历,循环数组
var arr=[1,2,3,4]; arr.forEach(alert); /* 等同于for循环 ***********/ for(var i=0;i<arr.length;i++){ alter(arr[i]); }
forEach
:参数
-
callback(value, index, array);【注:jq的$.each的callback(index, value, array)】
如果数组中的某个数被删除,array.length不会变,但循环是不会包含删除的
var sum=0, arr=[1,2,3,4]; arr.forEach(function(value, index, arr){ sum+=value; }); console.log(sum);//10; /* 使用jquery的each一样的结果 ***********/ $.each(arr,function(index,value, arr){ sum+=value; }); console.log(sum);//10
-
context:可选上下文参数(用来改变回调函数里面的this指向)
var data={ phones:["13254587621","128963","14587965847","123548963"], calling:function(phone){ if(this.isPhoneNum(phone)){ console.log("calling!"); }else{ console.log("Please call again!"); } }, isPhoneNum:function(phone){ return /^1\d{10}/g.test(phone); } }; data.phones.forEach(data.calling,data); //calling! //Please call again! //calling! //Please call again!
综上规则,针对IE6-IE8做扩展
if(typeof Array.prototype.forEach!=="function"){ Array.prototype.forEach=function(callback, context){ for(var i=0;i<this.length;i++){ if(typeof callback==="function" && Object.prototype.hasOwnProperty.call(this,i)){ callback.call(context,this[i],i,this); } } }; }
map
filter
some
every
indexOf
lastIndexOf
reduce
reduceRight