Javascript数组循环遍历之数组循环遍历之forEach详解详解
1.js 数组循环遍历。数组循环遍历。
数组循环变量,最先想到的就是 for(var i=0;i<count;i++)这样的方式了。
除此之外,也可以使用较简便的forEach 方式
2.forEach函数。函数。
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的方法。
3. 让让IE兼容兼容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;
评论0