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