⼿写js代码(⼀)javascript数组循环遍历之forEach
我这⾥是仿照学习!
1、js的数组循环遍历
  ①数组的遍历⾸先想到的是for()循环语句
var arr = ['summer','i','love', 'you'];
for(var i=0, length=arr.length; i<length; i++)
{
alert(arr[i]);
}
②其次,⽐较简单的⽅法 forEach()
FireFox 和Chrome的Array类型都有forEach()⽅法,但IE的Array类型没有forEach()⽅法。
var arr = ['summer','i','love', 'you'];
/*也可以这样来定义这个数组
  var arr = [];
  arr.push('summer');
  arr.push('i');
  arr.push('love');
  arr.push('you');
*/
//遍历数组,直接调⽤Array类型的prototype上⾯的forEach()⽅法
arr.forEach(function(e){
alert(e);
})
2、让IE兼容数组的forEach()⽅法
//IE中
alert(Array.prototype.forEach) // undefined
上⾯的代码说明了IE中的Array类型没有forEach()⽅法
好,既然IE的Array类型没有forEach()⽅法,那我们现在给它加上forEach()⽅法
//Array.forEach implementation for IE support..
///en/JavaScript/Reference/Global_Objects/Array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
javascript数组对象var O = Object(this);
var len = O.length >>> 0; // Hack to convert O.length to a UInt32
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
IE中定义好了之后,Array类型上⾯就有了forEach()⽅法,就可以调⽤了。
var arr=[1,2,3];
arr.forEach(function(e){alert(e)}); //依次弹出1,2,3
3、forEach(callback)⽅法中传⼊的是callback ,callback为⼀个回调函数——即每次遍历都会调⽤的函数
⽐如,其实forEach()⾥⾯传⼊的回调函数其实是以前我们写在for()循环体{}⾥⾯的代码,这其实就是⼀种抽象,更明朗,我们把以前写在for() {}循环体{}⾥⾯的代码(处理过程)放到⼀个函数中去,然后作为参数传⼊forEach()⽅法中。。这也是js中将函数作为参数传递的⼀个体现。//取出数组中能被2或3整除的数
var oldArr = [1,2,3,4,5,6,7,8];
var newArr = [];  //var  new =[]; this will be error ,the "new " is the key world in javascript oldArr.forEach(function(e){
if(e%2 == 0){
newArr.push(e);
return ; //注意,这⾥不能⽤break;或者是continue;
}else if(e%3 == 0){
newArr.push(e);
return ;
}
})
其实,⼀看上⾯的这个取出数组中能被2,3整除的数逻辑显然不够简洁,下⾯改进var oldArr = [1,2,3,4,5,6,7];
var newArr = [];
oldArr.forEach(function(e){
if(e%2 ==0 || e%3==0){
newArr.push(e);
}
})