ES5 数组方法forEach

ES6已经到了非学不可的地步了,对于ES5都不太熟的我决定是时候学习ES5了。

1.  js 数组循环遍历。

数组循环变量,最先想到的就是 for(var i=0;i<count;i++)这样的方式了。

除此之外,也可以使用较简便的forEach 方式

2.  forEach 函数。

使用如下:

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

3.  让IE兼容forEach方法

  (1)既然IE的Array 没哟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++;  
        }  
    };  
}  

详细介绍可以参照:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach

(2)类似underscore的库

underscore的用法

_.each([1, 2, 3], function(e){
    alert(e);
});
=> alerts each number in turn...
_.each({one: 1, two: 2, three: 3}, function(e){
    alert(e)
});
=> alerts each number value in turn...

4. 如何跳出循环?

Js 此种状况的forEach 不能使用continue, break;  可以使用如下两种方式:
1. if 语句控制
2. return . (return true, false)
return --> 类似continue 

arryAll.forEach(function(e){  
    if(e%2==0)  
    {  
        arrySpecial.push(e);  
        return;  
    }  
    if(e%3==0)  
    {      
        arrySpecial.push(e);  
        return;  
    }  
})  
原文地址:https://www.cnblogs.com/leejersey/p/5457687.html