JavaScript 数组 indexOf()

indexOf() 方法返回数组元素第一次出现的索引,如果未找到则返回 -1

示例

let languages = ["Java", "JavaScript", "Python", "JavaScript"];

// get the index of the first occurrence of "JavaScript" let index = languages.indexOf("JavaScript");
console.log(index); // Output: 1

indexOf() 语法

indexOf() 方法的语法是:

arr.indexOf(searchElement, fromIndex)

这里,arr 是一个数组。


indexOf() 参数

indexOf() 方法接受

  • searchElement - 要在数组中查找的元素。
  • fromIndex(可选)- 开始搜索的索引。默认为 0

indexOf() 返回值

  • 如果数组中至少存在一次该元素,则返回该元素在数组中的第一个索引。
  • 如果在数组中未找到该元素,则返回 -1

注意: indexOf() 使用 严格相等(类似于三等于运算符或 ===)将 searchElement 与数组的元素进行比较。


示例 1:使用 indexOf() 方法

var priceList = [10, 8, 2, 31, 10, 1, 65];

// indexOf() returns the first occurance
var index1 = priceList.indexOf(31);
console.log(index1); // 3
var index2 = priceList.indexOf(10);
console.log(index2); // 0 // second argument specifies the search's start index
var index3 = priceList.indexOf(10, 1);
console.log(index3); // 4 // indexOf returns -1 if not found
var index4 = priceList.indexOf(69.5);
console.log(index4); // -1

输出

3
0
4
-1

注意事项

  • 如果 fromIndex >= array.length,则不搜索数组,并返回 -1
  • 如果 fromIndex < 0,则从后向前计算索引。例如,-1 表示最后一个元素的索引,依此类推。

示例 2:查找元素的所有出现次数

function findAllIndex(array, element) {
  indices = [];
var currentIndex = array.indexOf(element);
while (currentIndex != -1) { indices.push(currentIndex);
currentIndex = array.indexOf(element, currentIndex + 1);
} return indices; } var priceList = [10, 8, 2, 31, 10, 1, 65, 10]; var occurance1 = findAllIndex(priceList, 10); console.log(occurance1); // [ 0, 4, 7 ] var occurance2 = findAllIndex(priceList, 8); console.log(occurance2); // [ 1 ] var occurance3 = findAllIndex(priceList, 9); console.log(occurance3); // []

输出

[ 0, 4, 7 ]
[ 1 ]
[]

示例 3:查找元素是否存在,否则添加该元素

function checkOrAdd(array, element) {
if (array.indexOf(element) === -1) {
array.push(element); console.log("Element not Found! Updated the array."); } else { console.log(element + " is already in the array."); } } var parts = ["Monitor", "Keyboard", "Mouse", "Speaker"]; checkOrAdd(parts, "CPU"); // Element not Found! Updated the array. console.log(parts); // [ 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ] checkOrAdd(parts, "Mouse"); // Mouse is already in the array.

输出

Element not Found! Updated the array.
[ 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ]
Mouse is already in the array.

推荐阅读: JavaScript Array.lastIndexOf()

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战