JavaScript 数组最后索引 lastindexof


JavaScript 数组最后索引 lastindexof

<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>