forEach是javascript中遍历数组的方法,大部分人常用for()循环来遍历数组,现在我们来看一下forEach的用法。

兼容性

Firefox 和Chrome 的Array 类型都有forEach的函数。使用如下:

<script>  
var arryAll = [];  
arryAll.push(1);  
arryAll.push(2);  
arryAll.push(3);  
arryAll.push(4);  
  
arryAll.forEach(function(e){  
    alert(e);  
})  
  
</script>  

但是在IE中却没有forEach这个方法 :alert(Array.prototype.forEach); //undefined

但是我们可以使用如下方法来让IE兼容这个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++;  
        }  
    };  
}  

凡是有循环的地方,都会涉及到跳出循环的情况,那么forEach如何跳出循环呢?
Js此种状况的forEach不能使用continue, break;可以使用如下两种方式:

  1. if 语句控制

  2. return (return true/return false) return --> 类似continue

例子:取出数组中3的倍数和7的倍数的数

<script>  
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(7);  
arryAll.push(21);  
arryAll.push(22);  
arryAll.push(28);  
var arrySpecial = [];  
arryAll.forEach(function(e){  
    if(e%2==0)  
    {  
        arrySpecial.push(e);  
    }else if(e%3==0)  
    {  
        arrySpecial.push(e);  
    }  
})
</script>  

CodeMan
1.4k 声望58 粉丝

《伤害》