ES5 数组方法forEach

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

1.  js 数组循环遍历。

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

 

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

 

2.  forEach 函数。

使用以下:this

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方法, 咱们就给它手动添加这个原型方法。spa

//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/forEachprototype

(2)相似underscore的库code

underscore的用法blog

_.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 three

arryAll.forEach(function(e){  
    if(e%2==0)  
    {  
        arrySpecial.push(e);  
        return;  
    }  
    if(e%3==0)  
    {      
        arrySpecial.push(e);  
        return;  
    }  
})  
相关文章
相关标签/搜索