Javascript Array.lastIndexOf()方法
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