JS 中的foreach和For in比较

使用方式举例如下:

<script type="text/javascript">
var jsonranklist=[{"name":"ts","code":123456,"topscore":2000},{"xlid":"tb","code":123456,"topscore":1500}];
console.log(jsonranklist.length);

//使用foreach循环
jsonranklist.forEach(function(e){
        console.log(e.xlid);
      });
//使用for in 循环 for (var cindxe in jsonranklist) { //var obj=JSON.stringify(dt); console.log(jsonranklist[cindxe].xlid); } </script>

但是IE7之前的版本并不支持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++;
        }
    };
}

完整参考代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Author" CONTENT="oscar999">
</HEAD>

<BODY>
<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(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);
    }
})

</script>
</BODY>
</HTML>

参考博客地址:
    http://blog.csdn.net/oscar999/article/details/8671546

posted @ 2015-05-19 09:16  jiajinhao  阅读(2506)  评论(0编辑  收藏  举报