WebGL Tutorial
and more

indexOf

撰写时间:2024-03-15

最新修订:2024-03-15

indexOf

返回元素在数组中第一次出现的索引值。

原型

numberindexOf
  • *element
  • numberfromIndex = 0

参数

element
要查找的元素。
fromIndex = 0
从哪个索引位置开始查找。若未指定,默认为0

返回值

如果要查找的元素在数组中有1或多次出现,则返回第一次出现的索引值。否则,返回-1

说明

indexOf方法返回元素在数组中第一次出现的索引值。

如果要查找的元素在数组中有1或多次出现,则返回第一次出现的索引值。否则,返回-1

例子

基本用法

let arr = [5, 8, 50, 8, 66]; console.log(arr.indexOf(8)); // 1

指定开始搜索的位置

let arr = ['a', 'b', 'c', 'd', 'e']; console.log(arr.indexOf('b', 2)); // -1

尽管b存在于数组中,但其索引值为1。而我们要求从索引值为2的位置开始查找b,则结果为-1

查找Object的实例

当要查找的元素的数据类型是Object时,将查找引用而非数值所在的索引值。

let arr = [{animal: "cat"}]; console.log(arr.indexOf({animal: "cat"})); // -1

数组arr中的元素{animal: "cat"},虽与indexOf方法中参数的数值相同,但它们并非同一对象,因此结果为-1

参见

  1. findIndex
  2. includes
  3. lastIndexOf

参考资源

  1. ECMA 262: Array Objects