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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。