indexof函数的使用方法

admin 27 0

`indexOf` 是 JavaScript 中的一个常用方法,通常用于数组(Array)对象,这个方法返回指定元素在数组中首次出现的索引,如果没有找到该元素,则返回 -1。

以下是 `indexOf` 方法的基本使用方法:

let array = [1, 2, 3, 4, 5];

let index = array.indexOf(3);  // 返回 2,因为 3 在数组中的索引是 2

如果你想查找一个元素在数组中是否存在,你可以使用 `indexOf` 方法的结果进行判断:

let array = [1, 2, 3, 4, 5];

if (array.indexOf(3) !== -1) {
  console.log('元素存在于数组中');
} else {
  console.log('元素不存在于数组中');
}

`indexOf` 方法还可以接受第二个参数,表示从哪个索引位置开始搜索。

let array = [1, 2, 3, 4, 5];

let index = array.indexOf(3, 2);  // 返回 -1,因为从索引 2 开始搜索,3 不存在于该位置及其之后的元素中

`indexOf` 方法是大小写敏感的,所以 'apple' 和 'Apple' 被视为两个不同的元素。