JavaScript 数组 lastIndexOf()
示例
查找“Apple”的最后一个索引
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
自己动手试一试 »
不止一个 Apple
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple");
自己动手试一试 »
更多示例见下文。
描述
lastIndexOf()
方法返回指定值的最后一个索引(位置)。
如果未找到该值,lastIndexOf()
方法返回 -1。
lastIndexOf()
从指定索引开始,从右到左(从给定位置到数组开头)搜索。
默认情况下,搜索从最后一个元素开始,到第一个元素结束。
负的起始值从最后一个元素开始计数(但仍然从右到左搜索)。
数组查找方法
方法 | 查找 |
---|---|
indexOf() | 具有指定值的第一个元素的索引 |
lastIndexOf() | 具有指定值的最后一个元素的索引 |
find() | 通过测试的第一个元素的值 |
findIndex() | 通过测试的第一个元素的索引 |
findLast() | 通过测试的最后一个元素的值 |
findLastIndex() | 通过测试的最后一个元素的索引 |
语法
array.lastIndexOf(item, start)
参数
参数 | 描述 | |
item | 必需。 要搜索的值。 |
|
start | 可选。 从哪里开始搜索。 默认是最后一个元素 (array.length-1)。 负的起始值从最后一个元素开始计数(但仍然从右到左搜索)。 |
返回值
类型 | 描述 |
一个数字 | 指定项目的位置。 如果未找到项目,则为 -1。 |
更多示例
从位置 4 开始搜索
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", 4);
自己动手试一试 »
从倒数第二个位置开始搜索
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", -2);
自己动手试一试 »
浏览器支持
lastIndexOf()
是 ECMAScript5 (ES5) 的一个特性。
自 2013 年 7 月以来,所有现代浏览器都完全支持 ES5 (JavaScript 2009)
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
2012 年 9 月 | 2012 年 9 月 | 2013 年 4 月 | 2012 年 7 月 | 2013 年 7 月 |