Javascript-array-filter

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

JavaScript-Array filter()メソッド

説明

Javascript配列* filter()*メソッドは、提供された関数によって実装されたテストに合格したすべての要素を含む新しい配列を作成します。

構文

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

array.filter(callback[, thisObject]);

パラメータの詳細

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

戻り値

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

互換性

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

if (!Array.prototype.filter) {
   Array.prototype.filter = function(fun/*, thisp*/) {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();

      var res = new Array();
      var thisp = arguments[1];
      for (var i = 0; i < len; i++) {
         if (i in this) {
            var val = this[i];  //in case fun mutates this
            if (fun.call(thisp, val, i, this))
            res.push(val);
         }
      }
      return res;
   };
}

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

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

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

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

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

               for (var i = 0; i < len; i++) {
                  if (i in this) {
                     var val = this[i];  //in case fun mutates this
                     if (fun.call(thisp, val, i, this))
                     res.push(val);
                  }
               }
               return res;
            };
         }
         function isBigEnough(element, index, array) {
            return (element >= 10);
         }
         var filtered  = [12, 5, 8, 130, 44].filter(isBigEnough);
         document.write("Filtered Value : " + filtered );
      </script>
   </body>
</html>

出力

Filtered Value : 12,130,44