JavaScript 数组lastIndexOf()方法返回在该给定元素可以数组找到的最后一个索引,或如果它不存在则返回-1。该数组搜索向后,从fromIndex开始。
语法
array.lastIndexOf(searchElement[, fromIndex])
下面是参数的详细信息:
-
searchElement%uA0: 定位数组中的元素
-
fromIndex%uA0: 索引在 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
%uA0