lastIndexOf(searchValue,fromIndex)--查找某个元素或子字符串在字符串或数组中最后一次出现的位置 ,找不到返回-1

68 阅读1分钟

lastIndexOf 是一个常用的方法,通常用于字符串和数组。在 JavaScript 中,lastIndexOf 方法用于查找某个元素或子字符串在字符串或数组中最后一次出现的位置。

在字符串中的用法

let str = "Hello, world! Hello again!";
let index = str.lastIndexOf("Hello");
console.log(index); // 输出: 13

在数组中的用法

let arr = [1, 2, 3, 2, 1];
let index = arr.lastIndexOf(2);
console.log(index); // 输出: 3

参数说明

  • searchElement:要搜索的元素或子字符串。
  • fromIndex(可选):开始搜索的位置,默认为数组/字符串的最后一个索引。

注意事项

  • 如果没有找到元素,lastIndexOf 会返回 -1。
  • 这个方法是区分大小写的。