lastIndexOf()
方法在 数组 中查找指定元素的最后一个出现位置,并返回其索引。
示例
let priceList = [10, 8, 2, 31, 10, 31, 65];
// finding the index of the last occurence of 31
let lastIndex = priceList.lastIndexOf(31);
console.log(lastIndex);
// Output: 5
lastIndexOf() 语法
lastIndexOf()
方法的语法是
arr.lastIndexOf(searchElement, fromIndex)
这里,arr 是一个数组。
lastIndexOf() 参数
lastIndexOf()
方法可以接受 **两个** 参数
- searchElement - 要在数组中查找的元素。
- fromIndex (可选) - 开始向后搜索的索引。默认为 array.length - 1。
lastIndexOf() 返回值
lastIndexOf()
方法返回
- 如果元素至少出现一次,则返回该元素在数组中的最后一个索引。
- 如果数组中未找到该元素,则返回 -1。
注意: lastIndexOf()
使用 **严格相等** (类似于三等号运算符或 ===
) 来比较 searchElement
和数组中的元素。
示例 1:使用 lastIndexOf() 方法
let alphabets = ["a", "b", "c", "a", "d"];
// finding the index of the last occurence of 'a'
let lastIndex1 = alphabets.lastIndexOf("a");
console.log(lastIndex1);
// finding the index of the last occurence of 'e'
let lastIndex2 = alphabets.lastIndexOf("e");
console.log(lastIndex2);
输出
3 -1
在上面的示例中,我们使用 lastIndexOf()
方法查找 'a'
和 'e'
的最后出现索引。
alphabets
中 'a'
的最后一次出现是在索引 **3**,因此 alphabets.lastIndexOf("a")
返回 **3**。
alphabets.lastIndexOf("e")
返回 **-1**,因为数组不包含 'e'
。
示例 2:带两个参数的 lastIndexOf()
let alphabets = ["a", "b", "c", "a", "d", "a"];
// second argument specifies the starting index
// from where the method searches the element backward
let lastIndex = alphabets.lastIndexOf("a", 4);
console.log(lastIndex);
输出
3
在上面的示例中,我们在 lastIndexOf()
方法中传递了第二个参数 **4**。
alphabets.lastIndexOf("a", 4)
从索引 **4** 开始向后搜索元素 'a'
,并返回 'a'
的最后一次出现,即 **3**。
示例 3:带负参数的 lastIndexOf()
如果 fromIndex 是负数,则索引会向后计算。例如
let alphabets = ["a", "b", "c", "a", "d"];
// starts the search at third last position
let lastIndex = alphabets.lastIndexOf("a", -3);
console.log(lastIndex);
输出
0
这里 alphabets.lastIndexOf("a", -3)
从数组的倒数第三个位置开始搜索,并返回 'a'
的最后一次出现,即 **0**。
推荐阅读