JavaScript array.forEach()方法为数组中的每个元素调用一个函数。

forEach() - 语法

array.forEach(callback[, thisObject]);
  • callback     -  用于测试数组的每个元素的回调函数。

  • thisObject  -  要在执行回调时的对象。

forEach() - 返回值

返回创建的数组..

forEach() - 相容性

此方法是ECMA-262标准的JavaScript扩展;因此,它可能不存在于该标准的其他实现中。要使其工作,您需要在脚本顶部添加以下代码。

if (!Array.prototype.forEach) {
   Array.prototype.forEach=function(fun /*, thisp*/) {
      var len=this.length;
      if (typeof fun != "function")
      throw new TypeError();
      
      var thisp=arguments[1];
      for (var i=0; i < len; i++) {
         if (i in this)
         fun.call(thisp, this[i], i, this);
      }
   };
}

forEach() - 示例

<html>
   <head>
      <title>JavaScript Array forEach Method</title>
   </head>
   
   <body>   
      <script type="text/javascript">
         if (!Array.prototype.forEach) {
            Array.prototype.forEach=function(fun /*, thisp*/) {
               var len=this.length;
               
               if (typeof fun != "function")
               throw new TypeError();
               
               var thisp=arguments[1];
               for (var i=0; i < len; i++) {
                  if (i in this)
                  fun.call(thisp, this[i], i, this);
               }
            };
         }
         function printBr(element, index, array) {
            document.write("<br />[" + index + "] is " + element ); 
         }
         [12, 5, 8, 130, 44].forEach(printBr);
      </script>      
   </body>
</html>

运行上面代码输出

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44 

参考链接

https://www.learnfk.com/javascript/array-foreach.html