string.indexOf(searchValue, fromIndex) -- 返回子字符串首次出现的索引,找不到返回-1 从左至右查找

295 阅读2分钟

indexOf 是 JavaScript 中的一个字符串和数组方法,主要用于查找某个元素在数组或字符串中的位置。它返回元素首次出现的索引,如果没有找到,则返回 -1从左至右查找。下面将分别介绍 indexOf 在字符串和数组中的使用,以及常见的使用场景。

语法

str.indexOf(searchElement, fromIndex);
  • searchElement: 要查找的元素。
  • fromIndex (可选): 开始查找的位置,默认为 0

使用场景

  • 查找元素: 确定数组中是否存在某个元素,并获取其索引。
  • 去重: 在执行某些操作(如推入新元素)之前,先检查元素是否已经存在于数组中。
  • 条件过滤: 在处理复杂数据结构时,根据元素的位置来进行特定的操作。

1. 字符串中的 indexOf

使用方法


const str = "Hello, world!";
const index = str.indexOf("world"); // 返回 7
const notFound = str.indexOf("Java"); // 返回 -1

语法

string.indexOf(searchValue, fromIndex);
  • searchValue: 要查找的字符串。
  • fromIndex (可选): 开始查找的位置,默认为 0

使用场景

  • 查找子字符串: 检查某个子字符串是否存在于字符串中,并获取其位置。
  • 验证输入: 确保用户输入的字符串中包含特定的字符或词语。

2. 数组中的 indexOf

使用方法

const arr = [10, 20, 30, 40];
const index = arr.indexOf(30); // 返回 2
const notFound = arr.indexOf(50); // 返回 -1

3. 示例

字符串示例

const sentence = "The quick brown fox jumps over the lazy dog.";
const word = "fox";

if (sentence.indexOf(word) !== -1) {
    console.log(`The word "${word}" is found at index ${sentence.indexOf(word)}.`);
} else {
    console.log(`The word "${word}" is not found.`);
}

数组示例

const fruits = ["apple", "banana", "cherry"];
const fruitToFind = "banana";

const index = fruits.indexOf(fruitToFind);
if (index !== -1) {
    console.log(`Found ${fruitToFind} at index ${index}.`);
} else {
    console.log(`${fruitToFind} is not in the array.`);
}

4. 注意事项

  • 区分大小写indexOf 在字符串查找时是区分大小写的。例如,"Hello".indexOf("hello") 返回 -1
  • 不支持 NaN: 对于数组,indexOf 无法查找 NaN。因此,使用 NaN 时应使用其他方法,如 Array.prototype.findIndex

总结

indexOf 是一个简单且强大的工具,用于在字符串数组中查找元素。通过掌握它的用法,可以在许多情况下提高代码的效率和可读性。