JavaScript array.lastIndexOf()方法返回可以在数组中找到给定元素的最后一个索引,如果不存在,则返回-1。从fromIndex开始向后搜索数组。
array.lastIndexOf(searchElement[, fromIndex]);
searchElement - 要在数组中定位的元素。
FromIndex - 开始向后搜索的索引。默认为数组的长度,即将搜索整个数组。如果索引大于或等于数组的长度,则将搜索整个数组。如果为负,则将其视为距数组末尾的偏移量。
返回找到的元素从最后一个元素开始的索引。
此方法是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; }; }
<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>
运行上面代码输出
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/array-lastindexof.html
来源:LearnFk无涯教程网
index is : 2 index is : 5
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)