forEach遍历数组实例

forEach()取出数组中2的倍数和3的倍数的数

//for IE
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++;
        }
    };
}

var arryAll = [];
arryAll.push(1);
arryAll.push(2);
arryAll.push(3);
arryAll.push(4);
arryAll.push(5);

var arrySpecial = [];

arryAll.forEach(function(e){
    if(e%2==0){
        arrySpecial.push(e);
    }else if(e%3==0){
        arrySpecial.push(e);
    }
});

 

posted on 2016-05-03 17:07  Cosimo  阅读(293)  评论(0编辑  收藏  举报

导航