JavaScript indexOf 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 indexOf
方法查找元素。该方法适用于数组和字符串。
indexOf 方法
indexOf
方法返回给定元素在数组或字符串中首次出现时的索引。如果元素不存在,则返回 -1。该方法在搜索时执行严格相等比较 (===)。
对于数组,它从开头开始搜索指定的值。对于字符串,它在字符串内搜索子字符串。这两个版本都可以接受一个可选的第二个参数,以指定搜索的起始位置。
indexOf
方法在使用字符串时区分大小写。它不会修改原始数组或字符串。该方法通常用于检查元素是否存在或查找其在集合中的位置。
基本数组 indexOf 示例
以下示例演示了 indexOf
方法与数组的基本用法。
const fruits = ['apple', 'banana', 'orange', 'grape']; const index = fruits.indexOf('banana'); console.log(index); // Position of 'banana' console.log(fruits.indexOf('pear')); // Not found
我们创建一个水果数组并搜索“banana”。该方法返回其位置 (1)。当搜索“pear”时,它返回 -1,因为它不在数组中。数组索引从 0 开始,因此第二个元素的索引为 1。
$ node main.js 1 -1
使用 fromIndex 查找元素
indexOf
方法可以接受第二个参数来指定搜索的起始位置。
const numbers = [1, 2, 3, 2, 1]; const firstTwo = numbers.indexOf(2); const secondTwo = numbers.indexOf(2, 2); console.log(firstTwo); // First occurrence console.log(secondTwo); // Second occurrence
我们在一个数组中搜索数字 2。第一次搜索从索引 0 开始。第二次搜索从索引 2 开始,跳过第一次出现。这演示了如何找到同一值的多个出现。
$ node main.js 1 3
字符串 indexOf 示例
indexOf
方法也可以与字符串一起使用来查找子字符串。
const text = 'Hello world, welcome to JavaScript'; const position = text.indexOf('world'); console.log(position); // Position of 'world' console.log(text.indexOf('World')); // Case-sensitive
我们在一个字符串中搜索子字符串“world”。该方法返回其起始位置 (6)。搜索区分大小写,因此“World”返回 -1。字符串索引也从 0 开始。
$ node main.js 6 -1
检查元素是否存在
indexOf
方法通常用于检查元素是否存在。
const colors = ['red', 'green', 'blue']; const hasGreen = colors.indexOf('green') !== -1; const hasYellow = colors.indexOf('yellow') !== -1; console.log(hasGreen); // true console.log(hasYellow); // false
我们检查“green”和“yellow”是否存在于数组中。通过与 -1 进行比较,我们将位置转换为布尔值。这是检查存在性的常见模式。现代 JavaScript 也为此提供了 includes
。
$ node main.js true false
查找所有出现
我们可以使用 indexOf
在循环中查找元素的所有出现。
const data = [1, 3, 5, 3, 7, 3, 9]; const target = 3; let indices = []; let currentIndex = -1; while ((currentIndex = data.indexOf(target, currentIndex + 1)) !== -1) { indices.push(currentIndex); } console.log(indices); // All positions of 3
我们在一个数组中找到数字 3 的所有出现。循环从最后一个找到的索引之后的位置开始搜索。每个找到的位置都添加到 indices 数组中。此技术适用于数组和字符串。
$ node main.js [ 1, 3, 5 ]
来源
在本文中,我们演示了如何使用 indexOf() 方法在 JavaScript 数组和字符串中查找元素。
作者
列出 所有 JS 数组函数。