目录

forEach()

描述 (Description)

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

语法 (Syntax)

其语法如下 -

array.forEach(callback[, thisObject]);

参数细节 (Parameter Details)

  • callback - 用于测试数组中每个元素的函数。

  • thisObject - 执行回调时用作此对象的对象。

返回值 (Return Value)

返回创建的数组..

兼容性 (Compatibility)

此方法是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);
      }
   };
}

例子 (Example)

请尝试以下示例。

<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>

输出 (Output)

[0] is 12
[1] is 5
[2] is 8
[3] is 130
[4] is 44 
↑回到顶部↑
WIKI教程 @2018