JavaScript 数组 foreach 循环


JavaScript 数组 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>