Javascript 数组循环遍历之forEach
1. js 数组循环遍历。
Firefox 和Chrome 的Array 类型都有forEach的函数。使用如下:
<!--Add by oscar999--> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Author" CONTENT="oscar999"> </HEAD> <BODY> <script> var arryAll = []; arryAll.push(1); arryAll.push(2); arryAll.push(3); arryAll.push(4); //匿名方式 arryAll.forEach(function(e){ alert(e); }) function t1(arg){alert(arg);} //非匿名方式 arryAll.forEach(t1,arryAll); </script> </BODY> </HTML>
但是以上,代码在IE中却无法正常工作。
因为IE的Array 没有这个方法
alert(Array.prototype.forEach);
执行以上这句得到的是 "undefined", 也就是说在IE 中 Array 没有forEach的方法。
既然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的倍数和3的倍数的数;
<!--Add by oscar999--> <!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); arryAll.push(6); arryAll.push(7); var arrySpecial = []; arryAll.forEach(function(e){ if(e%2==0) { arrySpecial.push(e); }else if(e%3==0) { arrySpecial.push(e); } }) </script> </BODY> </HTML>
使用return 达到以上效果
arryAll.forEach(function(e){ if(e%2==0) { www.2cto.com arrySpecial.push(e); return; } if(e%3==0) { arrySpecial.push(e); return; } })
下面的测试代码是我自己加上的。
var arryAll = []; arryAll.push(1); arryAll.push(2); arryAll.push(3); arryAll.push(4); arryAll.push(5); arryAll.push(6); arryAll.push(7); arryAll.forEach(function(e){ alert(e); if(e>3) return false; });
参考:http://www.2cto.com/kf/201303/195411.html
http://www.cnblogs.com/mq0036/p/4015885.html
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。