博学而笃志 切问而近思 仁在其中
详情
Javascript Array.lastIndexOf()方法
作者:--     发布时间:2019-11-20     评论:0     阅读:2

javascript 数组lastindexof()方法返回在该给定元素可以数组找到的最后一个索引,或如果它不存在则返回-1。该数组搜索向后,从fromindex开始。

语法

array.lastindexof(searchelement[, fromindex]);

下面是参数的详细信息:

  • searchelement : 定位数组中的元素

  • fromindex : 索引在 start 倒退搜索。默认为数组的长度,即整个数组将被搜索。如果该指数大于或等于该数组的长度,整个数组将被搜索。如果为负,它被作为从数组的端部的偏移量。

返回值:

返回从最后找到元素的索引

兼容性:

这种方法是一个javascript扩展到ecma-262标准;因此它可能不存在在标准的其他实现。为了使它工作,你需要添加下面的脚本代码在顶部:

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  

 



下一篇:测试
相关文章
loading......
最新动态
所有评论

loading......

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册