JavaScript Array lastIndexOf() 方法
实例 1
找到 "Apple" 的最后一个索引值:
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
index 输出结果:
2
尝试一下 »
实例 2
多个 "Apple,找到 "Apple" 的最后一个索引值:
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple");
index 输出结果:
5
尝试一下 »
定义和用法
lastIndexOf() 方法返回指定值的最后一个索引(位置)。
如果未找到指定值,lastIndexOf() 方法返回 -1。
lastIndexOf() 方法从指定的索引位置开始,从右向左(从指定位置到数组开头)搜索。
默认情况下,搜索从数组的最后一个元素开始,到第一个元素结束。
负数的起始索引从数组的最后一个元素开始计数(但仍然从右向左搜索)。
数组查找方法:
方法 | 描述 |
---|---|
indexOf() | 找到具有指定值的第一个元素的索引 |
lastIndexOf() | 找到具有指定值的最后一个元素的索引 |
find() | 找到通过测试的第一个元素的值 |
findIndex() | 找到通过测试的第一个元素的索引 |
findLast() | 找到通过测试的最后一个元素的值 |
findLastIndex() | 找到通过测试的最后一个元素的索引 |
浏览器支持
lastIndexOf() 是 ECMAScript 5(ES5)特性。
ES5(JavaScript 2009)自 2013 年 7 月起已在所有现代浏览器中完全支持。
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |
语法
array.lastIndexOf(item, start)
参数
参数 | 描述 |
---|---|
item | 必需。要搜索的值。 |
start | 可选。开始搜索的位置。默认为数组的最后一个元素(array.length - 1)。负数的起始索引从数组的最后一个元素开始计数(但仍然从右向左搜索)。 |
返回值
Type | 描述 |
---|---|
数字 | 指定值的位置。如果未找到该值,则返回 -1。 |
从索引 4 的位置开始搜索:
实例
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", 4);
let index = fruits.lastIndexOf("Apple", 4);
从倒数第二个位置开始搜索:
实例
const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", -2);
let index = fruits.lastIndexOf("Apple", -2);
点我分享笔记