Javascript Array.lastIndexOf()方法
作者:--
发布时间:2019-11-20
评论:0
阅读:2
javascript 数组lastindexof()方法返回在该给定元素可以数组找到的最后一个索引,或如果它不存在则返回-1。该数组搜索向后,从fromindex开始。
语法
array.lastindexof(searchelement[, fromindex]);
下面是参数的详细信息:
返回值:
返回从最后找到元素的索引
兼容性:
这种方法是一个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