Javascript-array-lastindexof

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

JavaScript-配列lastIndexOf()メソッド

説明

Javascript配列* lastIndexOf()メソッドは、指定された要素が配列内で見つかる最後のインデックスを返します。存在しない場合は-1を返します。 配列は、 *fromIndex から始まる逆方向に検索されます。

構文

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

array.lastIndexOf(searchElement[, fromIndex]);

パラメータの詳細

  • searchElement -配列内で検索する要素。
  • fromIndex -後方検索を開始するインデックス。 デフォルトは配列の長さです。つまり、配列全体が検索されます。 インデックスが配列の長さ以上の場合、配列全体が検索されます。 負の場合、配列の末尾からのオフセットと見なされます。

戻り値

最後から見つかった要素のインデックスを返します。

互換性

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

if (!Array.prototype.lastIndexOf) {
   Array.prototype.lastIndexOf = function(elt/*, from*/) {
      var len = this.length;
      var from = Number(arguments[1]);

      if (isNaN(from)) {
         from = len - 1;
      } else {
         from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);

         if (from < 0)
         from += len;

         else if (from >= len)
         from = len - 1;
      }

      for (; from > -1; from--) {
         if (from in this &&
         this[from] === elt)
         return from;
      }
      return -1;
   };
}

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

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

   <body>
      <script type = "text/javascript">
         if (!Array.prototype.lastIndexOf) {
            Array.prototype.lastIndexOf = function(elt/*, from*/) {
               var len = this.length;
               var from = Number(arguments[1]);

               if (isNaN(from)) {
                  from = len - 1;
               } else {
                  from = (from < 0)
                  ? Math.ceil(from)
                  : Math.floor(from);

                  if (from < 0)
                  from += len;

                  else if (from >= len)
                  from = len - 1;
               }
               for (; from > -1; from--) {
                  if (from in this &&
                  this[from] === elt)
                  return from;
               }
               return -1;
            };
         }
         var index = [12, 5, 8, 130, 44].lastIndexOf(8);
         document.write("index is : " + index );

         var index = [12, 5, 8, 130, 44, 5].lastIndexOf(5);
         document.write("<br/>index is : " + index );
      </script>
   </body>
</html>

出力

index is : 2
index is : 5