forEach


 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>菜鸟教程(runoob.com)</title>
 6 </head>
 7 <body>
 8 
 9 <p>点击按钮列出数组的每个元素。</p>
10 <button onclick="numbers.forEach(myFunction)">点我</button>
11 <p id="demo"></p>
12 
13 <script>
14 demoP = document.getElementById("demo");
15 var numbers = [4, 9, 16, 25];
16 
17 function myFunction(item, index) {
18     demoP.innerHTML = demoP.innerHTML + "index[" + index + "]: " + item + "<br>"; 
19 }
20 </script>
21 
22 </body>
23 </html>

 



语法:
array.forEach(function(currentValue, index, arr), thisValue)
currentValue: 必需。当前元素
index    :可选。当前元素的索引值。
arr      :可选。当前元素所属的数组对象。
thisValue  可选。传递给函数的值一般用 "this" 值。
        如果这个参数为空, "undefined" 会传递给 "this" 值

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<p>点击按钮计算数组所有元素相加的总和。</p>
<button onclick="numbers.forEach(myFunction)">点我</button>

<p>数组元素总和:<span id="demo"></span></p>

<script>
var sum = 0;
var numbers = [65, 44, 12, 4];

function myFunction(item) {
    sum += item;
    demo.innerHTML = sum;
}
</script>

</body>
</html>
//判断IE7\8 兼容性检测

2.对象不支持addEvntListener属性或方法

           var isIE=!!window.ActiveXObject;  
           var isIE6=isIE&&!window.XMLHttpRequest;  
           var isIE8=isIE&&!!document.documentMode;  
           var isIE7=isIE&&!isIE6&&!isIE8;  
              
           if(isIE8 || isIE7){  
               li.attachEvent("onclick",function(){  
                   _marker.openInfoWindow(_iw);  
               })      
           }else{  
               li.addEventListener("click",function(){  
                   _marker.openInfoWindow(_iw);  
               })  
           }  

  

1.javascript 如何解决IE8不支持forEach()

转载自:点击打开链接
forEach 是在第五版本里被添加到 ECMA-262 标准的;这样它可能在标准的其他实现中不存在,你可以在你调用 forEach 之前 插入下面的代码,在本地不支持的情况下使用 forEach()。该算法是 ECMA-262 第5版中指定的算法。算法假定ObjectTypeError拥有它们的初始值。callback.call 等价于Function.prototype.call()
if ( !Array.prototype.forEach ) {  
  Array.prototype.forEach = function forEach( 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;   
    if ( typeof callback !== "function" ) {  
      throw new TypeError( callback + " is not a function" );  
    }  
    if ( arguments.length > 1 ) {  
      T = thisArg;  
    }  
    k = 0;  
    while( k < len ) {  
      var kValue;  
      if ( k in O ) {  
        kValue = O[ k ];  
        callback.call( T, kValue, k, O );  
      }  
      k++;  
    }  
  };  
}  

  

 


 

posted @ 2017-11-12 12:52  你那么美,说什么都对  阅读(400)  评论(0编辑  收藏  举报