Javascript 中的 forEach()函数

首页 / JavaScript入门教程 / Javascript 中的 forEach()函数

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

forEach() - 语法

array.forEach(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 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

白话法律42讲 -〔周甲徳〕

从0开发一款iOS App -〔朱德权〕

TypeScript开发实战 -〔梁宵〕

人人都能学会的编程入门课 -〔胡光〕

Electron开发实战 -〔邓耀龙〕

系统性能调优必知必会 -〔陶辉〕

职场求生攻略 -〔臧萌〕

运维监控系统实战笔记 -〔秦晓辉〕

现代C++20实战高手课 -〔卢誉声〕

好记忆不如烂笔头。留下您的足迹吧 :)