试一试
const beasts = ["ant", "bison", "camel", "duck", "bison"];
console.log(beasts.indexOf("bison"));
// Expected output: 1
// Start from index 2
console.log(beasts.indexOf("bison", 2));
// Expected output: 4
console.log(beasts.indexOf("giraffe"));
// Expected output: -1
语法
js
indexOf(searchElement)
indexOf(searchElement, fromIndex)
参数
searchElement-
要在数组中定位的元素。
fromIndex可选-
开始搜索的基于零的索引,转换为整数。
- 负数索引从数组末尾开始计数 — 如果
-array.length <= fromIndex < 0,则使用fromIndex + array.length。请注意,在这种情况下,数组仍然从前向后搜索。 - 如果
fromIndex < -array.length或省略了fromIndex,则使用0,这将导致搜索整个数组。 - 如果
fromIndex >= array.length,则不搜索数组并返回-1。
- 负数索引从数组末尾开始计数 — 如果
返回值
数组中 searchElement 的第一个索引;如果未找到,则为 -1。
描述
indexOf() 方法使用严格相等(与 === 运算符使用的算法相同)比较 searchElement 与数组中的元素。 值永远不相等,因此当 NaNsearchElement 为 NaN 时,indexOf() 始终返回 -1。
indexOf() 方法会跳过稀疏数组中的空槽。
indexOf() 方法是通用的。它只期望 this 值具有 length 属性和整数键属性。
示例
使用 indexOf()
以下示例使用 indexOf() 在数组中查找值。
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。
js
const array = [NaN];
array.indexOf(NaN); // -1
查找元素的所有出现次数
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]
查找元素是否存在于数组中,以及更新数组
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()
您不能使用 indexOf() 搜索稀疏数组中的空槽。
js
console.log([1, , 3].indexOf(undefined)); // -1
在非数组对象上调用 indexOf()
indexOf() 方法读取 this 的 length 属性,然后访问键为小于 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
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.indexof |
浏览器兼容性
加载中…