Javascript 中的 lastIndexOf()函数

首页 / JavaScript入门教程 / Javascript 中的 lastIndexOf()函数

JavaScript array.lastIndexOf()方法返回可以在数组中找到给定元素的最后一个索引,如果不存在,则返回-1。从fromIndex开始向后搜索数组。

lastIndexOf() - 语法

array.lastIndexOf(searchElement[, fromIndex]);

lastIndexOf() - 返回值

返回找到的元素从最后一个元素开始的索引。

无涯教程网

lastIndexOf() - 相容性

此方法是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;
   };
}

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>

运行上面代码输出

index is : 2
index is : 5  

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

透视HTTP协议 -〔罗剑锋(Chrono)〕

编译原理之美 -〔宫文学〕

雷蓓蓓的项目管理实战课 -〔雷蓓蓓〕

性能工程高手课 -〔庄振运〕

恋爱必修课 -〔李一帆〕

流程型组织15讲 -〔蒋伟良〕

Spring编程常见错误50例 -〔傅健〕

程序员的个人财富课 -〔王喆〕

B端体验设计入门课 -〔林远宏(汤圆)〕

好记忆不如烂笔头。留下您的足迹吧 :)