手写js代码(一)javascript数组循环遍历之forEach

注:原文地址http://blog.csdn.net/oscar999/article/details/8671546

我这里是仿照学习!

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..
    //https://developer.mozilla.org/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");
            }
            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);
     }
})
原文地址:https://www.cnblogs.com/oxspirt/p/4283372.html