Javascript-array-map

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

JavaScript-配列map()メソッド

説明

Javascript配列* map()*メソッドは、この配列内のすべての要素で提供された関数を呼び出した結果を持つ新しい配列を作成します。

構文

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

array.map(callback[, thisObject]);

パラメータの詳細

  • callback -現在の配列の要素から新しい配列の要素を生成する関数。
  • thisObject -コールバックを実行するときに this として使用するオブジェクト。

戻り値

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

互換性

このメソッドは、ECMA-262標準のJavaScript拡張機能です。そのため、標準の他の実装には存在しない場合があります。 動作させるには、スクリプトの先頭に次のコードを追加する必要があります。

if (!Array.prototype.map) {
   Array.prototype.map = function(fun/*, thisp*/) {
      var len = this.length;

      if (typeof fun != "function")
      throw new TypeError();

      var res = new Array(len);
      var thisp = arguments[1];

      for (var i = 0; i < len; i++) {
         if (i in this)
         res[i] = fun.call(thisp, this[i], i, this);
      }
      return res;
   };
}

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

<html>
   <head>
      <title>JavaScript Array map Method</title>
   </head>

   <body>
      <script type = "text/javascript">
         if (!Array.prototype.map) {
            Array.prototype.map = function(fun/*, thisp*/) {
               var len = this.length;

               if (typeof fun != "function")
               throw new TypeError();

               var res = new Array(len);
               var thisp = arguments[1];

               for (var i = 0; i < len; i++) {
                  if (i in this)
                  res[i] = fun.call(thisp, this[i], i, this);
               }
               return res;
            };
         }
         var numbers = [1, 4, 9];
         var roots = numbers.map(Math.sqrt);
         document.write("roots is : " + roots );
      </script>
   </body>
</html>

出力

roots is : 1,2,3