Javascript-array-foreach

提供:Dev Guides
移動先:案内検索

JavaScript-Array forEach()メソッド

説明

Javascript配列* forEach()*メソッドは、配列内の各要素に対して関数を呼び出します。

構文

その構文は次のとおりです-

array.forEach(callback[, thisObject]);

パラメータの詳細

  • callback -配列の各要素をテストする関数。
  • thisObject -コールバックを実行するときにこれとして使用するオブジェクト。

戻り値

作成された配列を返します。

互換性

このメソッドは、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);
      }
   };
}

次の例を試してください。

<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