Array.prototype.indexOf()

Array 实例的 indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在则返回 -1。

¥The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.

Try it

语法

¥Syntax

js
indexOf(searchElement)
indexOf(searchElement, fromIndex)

参数

¥Parameters

searchElement

要在数组中定位的元素。

fromIndex Optional

开始搜索的从零开始的索引,转换为整数

  • 负索引从数组末尾开始倒数 — 如果使用 -array.length <= fromIndex < 0fromIndex + array.length。请注意,在这种情况下,仍然从前往后搜索数组。
  • 如果省略 fromIndex < -array.lengthfromIndex,则使用 0,导致搜索整个数组。
  • 如果是 fromIndex >= array.length,则不搜索数组并返回 -1

返回值

¥Return value

数组中 searchElement 的第一个索引;如果未找到,则为 -1

¥The first index of searchElement in the array; -1 if not found.

描述

¥Description

indexOf() 方法使用 严格平等(与 === 运算符使用的算法相同)将 searchElement 与数组的元素进行比较。NaN 值永远不会被比较为相等,因此当 searchElementNaN 时,indexOf() 始终返回 -1

¥The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN.

indexOf() 方法跳过 稀疏数组 中的空槽。

¥The indexOf() method skips empty slots in sparse arrays.

indexOf() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.

示例

¥Examples

使用 indexOf()

¥Using indexOf()

以下示例使用 indexOf() 来定位数组中的值。

¥The following example uses indexOf() to locate values in an array.

js
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

你不能使用 indexOf() 来搜索 NaN

¥You cannot use indexOf() to search for NaN.

js
const array = [NaN];
array.indexOf(NaN); // -1

查找某个元素的所有出现位置

¥Finding all the occurrences of an element

js
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]

查找数组中是否存在元素并更新数组

¥Finding if an element exists in the array or not and updating the array

js
function updateVegetablesCollection(veggies, veggie) {
  if (veggies.indexOf(veggie) === -1) {
    veggies.push(veggie);
    console.log(`New veggies collection is: ${veggies}`);
  } else {
    console.log(`${veggie} already exists in the veggies collection.`);
  }
}

const veggies = ["potato", "tomato", "chillies", "green-pepper"];

updateVegetablesCollection(veggies, "spinach");
// New veggies collection is: potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach already exists in the veggies collection.

在稀疏数组上使用 indexOf()

¥Using indexOf() on sparse arrays

你不能使用 indexOf() 搜索稀疏数组中的空槽。

¥You cannot use indexOf() to search for empty slots in sparse arrays.

js
console.log([1, , 3].indexOf(undefined)); // -1

对非数组对象调用 indexOf()

¥Calling indexOf() on non-array objects

indexOf() 方法读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

¥The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by indexOf() since length is 3
};
console.log(Array.prototype.indexOf.call(arrayLike, 2));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.indexof

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看